Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to sort some integers and make odd integers followed by even ones. I am using Visual Studio 2015.

Here's my code:

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.4k views
Welcome To Ask or Share your Answers For Others

1 Answer

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 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; });

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...