This post will discuss how to sort a vector in descending order in C++.

1. Use std::sort (or std::stable_sort)

An efficient solution is to use the std::sort algorithm defined in the <algorithm> header. It is usually a highly efficient implementation of the Introsort algorithm, which begins with quicksort and switches to heapsort when the recursion goes too deep.

The std::sort algorithm does not maintain the relative order of equal elements. To get a stable sort, go with std::stable_sort, which uses the mergesort algorithm.

 
The two-arg version of the std::sort algorithm sorts the vector in ascending order using operator<. To get the descending order, make a call to std::reverse after std::sort.

Download  Run Code

 
The above code requires an extra pass to reverse the vector. One can avoid the call to std::reverse by using reverse iterators.

Download  Run Code

2. Using std::sort + comparator

The std::sort function has another overloaded version that accepts a comparator. The comparator is a binary predicate that takes two arguments and returns a boolean value that determines whether the first argument appears before the second argument in the output sequence.

 
1. We can use std::greater as a comparator, which returns true if the first argument is more than the second argument. Starting from C++14, you can even skip the template arguments, i.e., std::greater<int>() becomes std::greater<>().

Download  Run Code

 
2. The comparator can be a simple binary function, or you can pass your own function object. You just need an instance of a class with operator() defined.

Download  Run Code

 
3. With C++11, you can even pass a lambda function to std::sort function.

Download  Run Code

3. Custom Sorting Routine

Finally, you can also write your own efficient routine for sorting the vector in descending order using quicksort, mergesort algorithms, etc.

That’s all about sorting a vector in descending order in C++.