Select Page

How to Sort a Vector in C++

by | C++, Programming, Tips

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.


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:

Have fun and happy researching!