You can sort a vector in C++ using the std::sort
function. This tutorial will go through how to sort a vector in ascending and descending order.
Table of contents
Sort a Vector using std::sort
The std::sort function sorts elements in the range [first, last)
in non-descending order. The order of equal elements is not guaranteed to be preserved. Let’s look at an example of sorting a vector of int in ascending order.
#include <iostream> #include <vector> int main() { // Vector of int std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8}; std::cout << "Elements before sorting" << std::endl; for (const auto &i: vec) std::cout << i << ' ' << std::endl; std::sort(vec.begin(), vec.end()); std::cout << "Elements after sorting" << std::endl; for (const auto &i: vec) std::cout << i << ' ' << std::endl; return 0; }
Let’s run the code to get the result:
Elements before sorting 9 1 5 10 11 0 7 3 2 4 8 Elements after sorting 0 1 2 3 4 5 7 8 9 10 11
We successfully sorted the elements in ascending order.
Sort a Vector in Descending Order using std::sort
The std::sort function takes a third parameter to specify the order to sort the elements in the vector. If we pass the std::greater function as the third parameter, the sorted elements will be in descending elements. Let’s look at the vector from the previous example sorted in descending order.
#include <iostream> #include <vector> int main() { // Vector of int std::vector<int> vec{9, 1, 5, 10, 11, 0, 7, 3, 2, 4, 8}; std::cout << "Elements before sorting" << std::endl; for (const auto &i: vec) std::cout << i << ' ' << std::endl; std::sort(vec.begin(), vec.end(), std::greater<>()); std::cout << "Elements after sorting" << std::endl; for (const auto &i: vec) std::cout << i << ' ' << std::endl; return 0; }
Let’s run the code to get the result:
Elements before sorting 9 1 5 10 11 0 7 3 2 4 8 Elements after sorting 11 10 9 8 7 5 4 3 2 1 0
We successfully sorted the elements in descending order.
Summary
Congratulations on reading to the end of this tutorial!
For further reading on C++, go to the articles:
- How to Convert Char Array to String in C++
- How to Reverse a String in C++
- How to Solve C++ Error: member reference type is a pointer; did you mean to use ‘->’?
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.