错误:“无效的比较器”使用自定义比较功能排序时 [英] Error:"invalid comparator" when sorting using custom comparison function

查看:82
本文介绍了错误:“无效的比较器”使用自定义比较功能排序时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试对一些整数进行排序,使奇数后跟偶数。我正在使用Visual Studio 2015。

I am trying to sort some integers and make odd integers followed by even ones. I am using 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
});

在执行时,遇到一个错误,提示表达式:无效的比较器。我不知道为什么会导致此错误。如何修改它?

When executed, it encounters an error says "Expression: invalid comparator". I don't know why it would cause this error. How to modify it?

推荐答案

sort 需要严格弱排序。您的比较器不是一个。除其他外,对于严格的弱排序, comp(x,x)必须为 false

sort requires a strict weak ordering. Your comparator isn't one. Among many other things, for a strict weak ordering, comp(x, x) must be false.

sort 仍然是错误的算法(是的,您可以将其扭曲以执行所需的操作;不,您不应不这样做)。您想要做的是一个分区。为此,我们有 std :: partition

sort is the wrong algorithm for this anyway (yes, you can contort it to do what you want; no, you shouldn't do it). What you want to do is a partition. For that, we have std::partition:

std::partition(std::begin(w), std::end(w), [](int x) { return x % 2 != 0; });

std :: stable_partition ,如果您希望分区稳定(保留元素的相对顺序)。

Or std::stable_partition, if you want the partition to be stable (preserve the relative order of elements).

这篇关于错误:“无效的比较器”使用自定义比较功能排序时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆