How to sort a Vector in ascending order using STL in C++?
In this article, we will be discussing how to sort a given vector in ascending with the help of the STL algorithm.
ALSO READ : How to sort a vector in descending order
Example:
Input:
vec = {12, 35, 44, 54, 23, 24, 87},
Output: {12, 23, 24, 35, 44, 54, 87}
Input:
vec = {12, 17, 25, 74, 60, 52,11},
Output: {11, 12, 17, 25, 52, 60, 74 }
How to sort a vector in ascending 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())
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 ascending 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 : 12, 23, 24, 35, 44, 54, 87
Post a Comment: