confusion about using std::less and std::greater with std::sort

std::sort sorts in ascending order by default. In case you are looking for descending order, here's the trick:

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::vector<int> vec(x, x+10);          // construct std::vector object
std::sort(vec.rbegin(),vec.rend());     // sort it in reverse manner

This way, you explicitly say that std::sort should treat your array as its end is its beginning and vice versa, which results in your array being sorted in descending order. Here's the full example.


And in case you want to use std::less and std::greater, then it could look like this:

int x[10] = { 1,3,5,7,9,2,4,6,8,10 };
std::sort(x, x + 10, std::less<int>());     // for ascending order
std::sort(x, x + 10, std::greater<int>());  // for descending order

Full example with second solution is here.


std::sort behaves like that because it's based on the idea of a strict weak ordering, which is (usually) defined in terms of the < operator.

As to your question; it currently seems to be "I wrote a C function that behaves differently to std::sort. Why is it different?". The answer is: because you wrote a different function!

Tags:

C++

C

Sorting

Stl

Std