How to Sort a Vector in Descending Order Using STL in C++?
Last Updated :
11 Nov, 2024
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.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {6, 8, 2, 9};
// Sort the vector
sort(v.begin(), v.end(), greater<>());
for (auto i : v)
cout << i << " ";
return 0;
}
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.
Using sort() with reverse()
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.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {6, 8, 2, 9};
// Sorting the vector
sort(v.begin(), v.end());
// Reversing the vector
reverse(v.begin(), v.end());
for (auto i : v)
cout << i << " ";
return 0;
}
Using stable_sort() with Custom Comparator
The stable_sort() function is similar to sort() function, but it preserves the relative order of equal elements.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {6, 8, 2, 9};
// sort the vector
stable_sort(v.begin(), v.end(), greater<>());
for (auto i : v)
cout << i << " ";
return 0;
}
Explanation: The stable_sort() function sorts the vector in ascending order. greater<>() is used as comparator to sort the vector in descending order.
Using Multiset
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.
C++
#include <bits/stdc++.h>
using namespace std;
int main() {
vector<int> v = {6, 8, 2, 9};
// Create multiset from vector
multiset<int> ms(v.begin(), v.end());
v.clear();
// Insert all elements back to vector
// in reverse order
copy(ms.rbegin(), ms.rend(),
back_inserter(v));
for (auto i : v)
cout << i << " ";
return 0;
}
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.