Sorting a range
In the previous recipe, we looked at the standard general algorithms for searching in a range. Another common operation we often need to do is sorting a range because many routines, including some of the algorithms for searching, require a sorted range. The standard library provides several general algorithms for sorting ranges, and in this recipe, we will see what these algorithms are and how they can be used.
Getting ready
The sorting general algorithms work with ranges defined by a start and end iterator and, therefore, can sort standard containers, arrays, or anything that represents a sequence and has random iterators available. However, all the examples in this recipe will use std::vector
.
How to do it...
The following is a list of standard general algorithms for searching a range:
- Use
std::sort()
for sorting a range:std::vector<int> v{3, 13, 5, 8, 1, 2, 1}; std::sort(v.begin(), v.end()); // v = {1, 1, 2, 3, 5, 8, 13...