CodeBlanks Logo Icon CodeBlanks

std::sort

Learn to sort with std::sort.

std::sort

std::sort sorts a range in place. It takes two iterators: std::sort(v.begin(), v.end()). By default it sorts in ascending order (small to large). It is defined in <algorithm>.

Sorting requires random access iterators; that is why it works on std::vector and std::array but not on std::list. The sort is efficient (usually O(n log n)). It modifies the container directly and does not create a new one. That is why it is called an 'in-place' sort.

Descending sort

To sort descending, pass std::greater<int>() as the third parameter: std::sort(v.begin(), v.end(), std::greater<int>());. This uses the > operator to sort large to small.

std::greater is a functor defined in <functional>. A functor is a class with operator(); it can be called like a function. At an advanced level you can write your own functors or use lambdas, but ready-made functors like std::greater cover most cases.

Practice Sort and print a vector

Sort the vector v = {5, 2, 8, 1, 9} in ascending order with std::sort. Then print each element followed by a space in a for loop.

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {5, 2, 8, 1, 9};
    // Sort with std::sort, print with a for loop
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {5, 2, 8, 1, 9};
    std::sort(v.begin(), v.end());
    for (int x : v) {
        std::cout << x << " ";
    }
    return 0;
}

Expected output

1 2 5 8 9

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 How does std::sort order by default?

main.cpp
std::sort(v.begin(), v.end());
  • Descending (large to small)
  • Randomly
  • Reversed
  • Ascending (small to large) Correct answer

Explanation: The default is ascending order.

2 Complete the sort call

Question
std::____(v.begin(), v.end());
Answer
std::sort(v.begin(), v.end());

Explanation: std::sort sorts the range.

3 Match each piece to its role

Term Meaning
std::sort(begin, end) Ascending sort
std::greater<int>() Descending sort
v.begin() Range start
v.end() Range end

All lessons in Intermediate