Sorting using STL

In C++ when we use sort function from STL. What exactly is that third argument and how does it work? How can we use it for stuffs other than ascending and descending sort?
For example, in the contest Cranium 2013, anton_lunyov used that third argument for something which was not asc or dsc sorting. His solution.

3 Likes

hi
see this link http://cplusplus.com/reference/algorithm/sort/?kw=sort

1 Like

The third functions is used to determine the ordering of the elements.

Basically the std::sort functions uses the 3rd argument (lets call it comp) to determine the relative ordering between 2 elements.
This comp must be a function that returns a boolean and must accept 2 parameters of the same type as the elements of the vector to be sorted.

Suppose we have a vector list;
and we have to sort the elements in such a manner that if func(T1) > func(T2) then T1 should come before T2 in the sorted vector.
Then we can write it as

bool comp(const T &a, const T &b)
{
return func(a) > func(b);
} // true signifies that a should come before b in the list
sort(list.begin(), list.end(), comp);

2 Likes