错误:使用自定义比较功能排序时"invalid comparator"

Error:"invalid comparator" when sorting using custom comparison function

本文关键字:排序 invalid comparator 功能 比较 自定义 错误      更新时间:2023-10-16

我正在尝试排序一些整数,使奇数后面跟着偶数。我使用的是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,如果您希望分区是稳定的(保持元素的相对顺序)