![]() |
VOOZH | about |
Sorting vector in descending order means arranging the elements in such a way that the first element will be largest, and second element will be second largest and so on.
In C++, the simplest way to sort the vector in descending order is to by using the sort() function with a custom comparator.
9 8 6 2
Explanation: The std::sort() function sorts a vector in ascending order by default. So, greater<>() function object is used to change the sorting order to descending order.
If a custom comparator is not available, just use the simple sort() function to sort the vector in ascending order and then reverse the order using reverse() function.
9 8 6 2
The stable_sort() function is similar to sort() function, but it preserves the relative order of equal elements.
9 8 6 2
Explanation: The stable_sort() function sorts the vector in ascending order. greater<>() is used as comparator to sort the vector in descending order.
A C++ multiset stores elements in ascending order by default. So, insert all elements from the vector into the multiset, then copy them back to the vector in reverse order.
9 8 6 2
Explanation: The multiset rbegin() and rend() return the reverse iterators which are then used by the copy() function to copy all the elements of multiset back to vector in reverse order.