错误:使用自定义比较功能排序时"invalid comparator"
Error:"invalid comparator" when sorting using custom comparison function
我正在尝试排序一些整数,使奇数后面跟着偶数。我使用的是Visual Studio 2015。
下面是我的代码:
int w[]={1,2,3,4,5,6};
sort(w,w+6,[](const int&i,const int&j)->bool {
return (i&1)==(j&1)//When both are odd or even, the order is OK
||i&1;//if one is odd and one is even,check if the first one is odd
});
当执行时,它遇到一个错误,说"表达式:无效的比较器"。我不知道为什么会导致这个错误。如何修改?
sort
要求严格弱排序。你的比较对象不是一个。其中,对于严格弱排序,comp(x, x)
必须是false
。
sort
是错误的算法(是的,你可以扭曲它来做你想做的;不,你不应该这么做)。您要做的是创建一个分区。为此,我们输入std::partition
:
std::partition(std::begin(w), std::end(w), [](int x) { return x % 2 != 0; });
或std::stable_partition
,如果您希望分区是稳定的(保持元素的相对顺序)
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 如何解决"invalid conversion from 'char' to 'const char*'"
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- 插入排序的Valgrind Invalid读取尺寸8的尺寸
- 排序 C++ - "invalid operator"
- 错误:使用自定义比较功能排序时"invalid comparator"
- 具有额外参数'invalid operator <'的 c++ STL 排序