In this C++ tutorial, you shall learn how to sort an integer vector in descending order, with example programs.
Sort integer Vector in descending order in C++
To sort elements in an integer vector in descending order in C++, use std::sort()
function of algorithm
library, and std::reverse()
function.
std::sort()
function of algorithm
library sorts the vector in ascending order, then reverse this vector using std::reverse()
function.
The statement to sort the elements of integer vector v
in descending order is
</>
Copy
sort(v.begin(), v.end());
reverse(v.begin(), v.end());
C++ Program
In the following program, we take an integer vector in v1
and sort this vector in descending order.
main.cpp
</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
//int vector
vector<int> v1 { 4, 17, 1, 8, 2, 15, 13 };
//sort vector v1 in descending order
sort(v1.begin(), v1.end());
reverse(v1.begin(), v1.end());
//print result vector
for ( auto& n : v1 ) {
cout << n << " ";
}
}
Output
17 15 13 8 4 2 1
Conclusion
In this C++ Tutorial, we learned how to sort given integer vector in descending order.