I was reading this code (source):
#include <iostream>
#include <functional>
#include <algorithm>
using namespace std;
int main() {
int number[] = {3, 5, 1, 6, 9};
auto print = [](int n) { cout << n << " "; };
sort(begin(number), end(number), [](int n1, int n2) { return n2 - n1; });
// result: 9 6 1 5 3
for_each(begin(number), end(number), print);
cout << endl;
sort(begin(number), end(number), [](int n1, int n2) { return n1 - n2; });
// result: 3 5 1 6 9
for_each(begin(number), end(number), print);
cout << endl;
return 0;
}
And I am confused about how return n2 - n1; vs return n1 - n2; work.
According to std::sort - cppreference.com, it says the comp is a bool type function. And in C++, non-zero numbers always have true value (according to Do negative numbers return false in C/C++? - Stack Overflow).
So the number in the example above has different items inside will always cause two of those lambda functions to return true. That is to say, those lambda functions return same results in this case. But the result show that one is in the reversed order and one is in the original order.
How can I explain this or what do I miss?