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