c++ - 如何排序 std::vector 忽略某些数字?
问题描述
我正在尝试对数字向量进行排序并忽略某个数字,即将它留在原处。这个答案实际上并没有留下找到它的元素。
例如,如果我有以下
std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
std::sort(test.begin(),
std::partition(test.begin(), test.end(), [](int n)
{return n != -1;}));
排序test
为1 3 4 5 6 8 9 11 -1
. 我搜索了几个小时,并修改了自定义比较器和 using std::partition
,但我无法提出将test
向量分类为1 3 4 5 -1 6 8 9 11
. 这实际上非常困难吗?
解决方案
根据@Bathsheba 在他的回答中提到的补救措施和愚弄std::sort()
的谓词,可以实现如下解决方案:
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> test{5, 3, 8, 4, -1, 1, 11, 9, 6};
// get the position of -1
auto itr = std::find(test.begin(), test.end(), -1);
// sort all elements so that -1 will be moved to end of vector
std::sort(test.begin(), test.end(), [](const int& lhs, const int& rhs )
{
if( lhs == -1 ) return false;
if( rhs == -1 ) return true;
return lhs < rhs;
});
test.erase(test.end()-1); // now erase it from end
test.insert(itr, -1); // insert to the earlier position
for(const auto& it: test) std::cout << it << " ";
return 0;
}
推荐阅读
- c# - LINQ Skip and limit with ordering 导致奇怪的结果
- angular - 在 Angular 7 中使用 routerLink 时,材质仪表板未显示在导航示意图中
- netty - 从 Netty 中的 FullHttpResponse byteBuf 获取字符串内容
- java - 在crxde中自动安装bundle的问题
- electron - Electron bulder 未处理的拒绝 HttpError: 404 Not Found on private repo
- swift - 一个集合不相等,但是这个集合中的一个数组是相等的?
- mysql - 我不知道如何使用 angular7 删除值
- ruby-on-rails - 从 Rails 视图中删除逻辑
- python - 在 matplotlib 中的 x 轴和 y 轴位置上绘制值时面临问题
- macos - 防止 IntelliJ IDEA 生成报告分配失败 - JavaScript 堆内存不足