To sort a vector in ascending order in C++, you can use the sort
function available in the <algorithm>
header.
In this example,
<vector>
.vec
containing several numeric values.sort
function, passing the beginning and end iterators of the vector as arguments. This function sorts the elements of the vector in ascending order.for
loop.#include <iostream>
#include <vector>
#include <algorithm>
int main() {
// Step 1: Create a vector
std::vector<int> vec = {5, 2, 8, 3, 9, 1};
// Step 2: Sort the vector in ascending order
std::sort(vec.begin(), vec.end());
// Step 3: Print the sorted vector
std::cout << "Sorted vector: ";
for (int num : vec) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
Sorted vector: 1 2 3 5 8 9
In this tutorial, we learned How to Sort a Vector in Ascending Order in C++ language with well detailed examples.