我正在尝试对一些整数进行排序,使奇数后面跟着偶数。我正在使用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
});在执行时,它会遇到“表达式:无效比较器”的错误。我不知道为什么它会导致这个错误。如何修改?
发布于 2015-08-28 13:06:17
sort需要strict weak ordering。你的比较器不是一个。其中,对于严格的弱排序,comp(x, x)必须为false。
sort无论如何都是错误的算法(是的,你可以扭曲它来做你想做的事情;不,你不应该这样做)。你想要做的是分区。为此,我们使用了std::partition
std::partition(std::begin(w), std::end(w), [](int x) { return x % 2 != 0; });或者std::stable_partition,如果您希望分区是稳定的(保持元素的相对顺序)。
https://stackoverflow.com/questions/32263560
复制相似问题