Loading lessons...
Algorithms
Algorithms
The <algorithm> header holds the "what to do" part of the STL. The algorithms work on [begin, end) ranges, which are exactly the iterators from the previous lesson.
Sort
#include <algorithm>
#include <vector>
std::vector<int> v = {5, 2, 7, 1};
std::sort(v.begin(), v.end());
// v is now {1, 2, 5, 7}
sort rearranges the whole range into ascending order. Give it the two-iterator range.
Find
auto it = std::find(v.begin(), v.end(), 7);
if (it != v.end()) {
std::cout << "found\n";
}
find returns an iterator to the first match, or end() when nothing matches.
Count
int c = std::count(v.begin(), v.end(), 2);
count sums how many times a value appears inside the range.
min_element and max_element
auto smallest = std::min_element(v.begin(), v.end());
auto largest = std::max_element(v.begin(), v.end());
std::cout << *smallest << " " << *largest; // 1 7
Both return iterators, so dereference them to read the actual values.
Why iterators bind it together
Every algorithm takes the same shape: algorithm(begin, end, ...). That is why the library can sort a vector, find a value in a list, or count inside an array - one concept, all containers.
TL;DR
- Algorithms live in
<algorithm>and work on iterator ranges. sort(begin, end)sorts;find(begin, end, value)returns an iterator orend().count(begin, end, x)tallies appearances of x.min_elementandmax_elementreturn iterators to the smallest or biggest element.- One range pattern works across every container.