Should std::sort work with lambda function in c++0x/c++11?
The comparison predicate should return a bool: true if a < b and false otherwise. Change the return statement to:
return a < b;
Not to be confused with C-style 3-way comparison functions.
NOTE: Though C++20 does introduce a 3-way comparison operator <=>
, sort
would still expect a 2-way compare predicate.
The predicate is supposed to implement a simple, weak ordering. Also your range is off if you want to sort the entire thing. (I missed that that was intentional.) So all in all we're looking for something like this:
std::sort(intArr, intArr + nelems, [](int a, int b){ return a < b; });
Or even:
std::sort(intArr, intArr + nelems);
The default predicate for sorting is std::less<T>
, which does exactly what the lambda does.
The predicate for std::sort
doesn't take the Java-like -1,0,1
, but instead wants you to return a boolean that answers the question 'Is the first argument less than the second argument?', which is used to weakly order the elements. Since -1
is a non-zero value, it is considered true by the sort algorithm, and it causes the algorithm to have a breakdown.