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