how to sort in descending order using stl...

Since using stl one can sort a vector using sort(vec.begin(),vec.end()); method but in ascending order.

So can anyone please tell how to sort in descending order?

2 Likes

For sorting in descending order, call sort function as

sort(vec.begin(), vec.end(), greater< int >() );
5 Likes

Its equally easy doing without stl. Have a look.

1 Like

You can use reserve iterator despite using function comparison.
Here is my sample code: http://ideone.com/IHPIXI

1 Like

Thankz…

Thankz…

Thankz…

btw how do it work by just adding cmp?

Just sort in ascending order and reverse the order.

sort(v.begin(),v.end());
reverse(v.begin(),v.end());

Tada!

1 Like

Sorting is done as per the definition of function. The concept is very similar to qsort(if you know what it is else see this http://www.cplusplus.com/reference/cstdlib/qsort/ ). The function is reordering the values in the array. For any two arguments, if a>b it returns 1 and when the return value is 1, the element pointed to by a appears before than the one pointed to by b. So, it in the sense is just swapping the contents or reordering.

1 Like