How to sort a Vector in descending order using STL in C++?


In this tutorial, we will be discussing a program to understand how to sort a vector in descending order using STL in C++.

For sorting the given vector in descending order we will be using the sort() function from the STL library in C++.

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   //collecting the vector
   vector<int> a = { 1, 45, 54, 71, 76, 12 };
   cout << "Vector: ";
   for (int i = 0; i < a.size(); i++)
      cout << a[i] << " ";
   cout << endl;
   //sorting in descending order
   sort(a.begin(), a.end(), greater<int>());
   cout << "Sorted Vector in descending order: ";
   for (int i = 0; i < a.size(); i++)
      cout << a[i] << " ";
   cout << endl;
   return 0;
}

Output

Vector: 1 45 54 71 76 12
Sorted Vector in descending order: 76 71 54 45 12 1

Updated on: 02-Mar-2020

367 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements