How to sort a Vector in descending order using STL in C++?
In this article, we will be discussing how to sort a given vector in descending with the help of the STL algorithm.
ALSO READ : How to sort a vector in ascending order
Example:
Input:
vec = {12, 35, 44, 54, 23, 24, 87},
Output: {87, 54, 44, 35, 24, 23, 12}
Input:
vec = {12, 17, 25, 74, 60, 52,11},
Output: {74, 60, 52, 25, 17, 12, 11 }
How to sort a vector in descending order :
We are going to use a predefined function that has been described in STL algorithms this function is sort()
. Using this function we will get our output.
Syntax
sort(vec.begin(), vec.end() , greater<T>());
//here T is the data type { ex: int, float, double ..
What is the use of greater<T>() :
This is a predefined function inside the STL library who resembles two elements while sorting and return greater element first. This is the logic for applying greater<T>() for sorting the vector in descending order.
Implementation :
#include<iostream>
#include<vector>
#include <algorithm>
int main()
{
// INtialize and store the vector
std::vector<int> vec = {12, 35, 44, 54, 23, 24, 87};
// We need to sort the vector the vector in descending order
std::sort(vec.begin(), vec.end(),greater<int>());
// Printout the sorted vector
std::cout << "Sorted Vector : ";
for (int i = 0; i < vec.size(); i++)
{
std::cout << vec1.at(i) << " ";
}
std::cout << std::endl;
return 0;
}
Output
Sorted Vector : 87 54 44 35 24 23 12
Post a Comment: