C++ STL Algorithms
C++ STL algorithms are reusable functions that process ranges of elements. They can sort, search, count, copy, and transform data stored in STL containers.
Most algorithms work with iterators, so the same algorithm can often be used with different containers.
Including Algorithms
Many common STL algorithms are declared in the <algorithm> header. To use them, include #include <algorithm> along with the header for the container you are using.
Algorithms usually receive a range written as two iterators: the first element to include and the position one past the last element. For a whole vector, that range is usually values.begin(), values.end().
Sorting, Finding, and Counting
This example uses three common algorithms:
std::sort()rearranges values into ascending order.std::find()searches for a specific value.std::count_if()counts values that match a condition.
#include <algorithm>
#include <iostream>
#include <vector>
int main(void) {
std::vector<int> scores = {88, 72, 95, 72, 100};
std::sort(scores.begin(), scores.end());
std::cout << "Sorted scores:" << std::endl;
for (int score : scores) {
std::cout << score << std::endl;
}
std::vector<int>::iterator found = std::find(scores.begin(), scores.end(), 95);
if (found != scores.end()) {
std::cout << "Found: " << *found << std::endl;
}
int passing = std::count_if(scores.begin(), scores.end(), [](int score) {
return score >= 80;
});
std::cout << "Passing scores: " << passing << std::endl;
return 0;
}
Output:
Sorted scores:
72
72
88
95
100
Found: 95
Passing scores: 3
How the Example Works
std::sort(scores.begin(), scores.end()) changes the order of the vector itself. After that call, the vector stores 72, 72, 88, 95, and 100.
std::find() returns an iterator. If the value is found, the iterator points to the matching element. If it is not found, the result is scores.end(), so the program checks for that before using *found.
std::count_if() uses a predicate, which is a condition that returns true or false. In this example, the lambda function returns true for scores greater than or equal to 80.
Algorithms Do Not Always Modify Data
Some algorithms change the range, while others only inspect it. For example, std::sort() modifies the container, but std::find() and std::count_if() only read from it.
| Algorithm | Purpose | Changes elements? |
|---|---|---|
std::sort() |
Put elements in order | Yes |
std::find() |
Find a value | No |
std::count() |
Count equal values | No |
std::count_if() |
Count values matching a condition | No |
std::reverse() |
Reverse element order | Yes |
Using a Custom Sort Rule
Some algorithms can receive a comparison function. For std::sort(), the comparison decides which value should come first.
This program sorts names by length. If two names have the same length, it sorts those names alphabetically.
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main(void) {
std::vector<std::string> names = {"Mia", "Alexander", "Bo", "Ava"};
std::sort(names.begin(), names.end(), [](const std::string& a, const std::string& b) {
if (a.length() == b.length()) {
return a < b;
}
return a.length() < b.length();
});
for (const std::string& name : names) {
std::cout << name << std::endl;
}
return 0;
}
Output:
Bo
Ava
Mia
Alexander
The lambda compares two strings at a time. It returns true when the first string should appear before the second string.
Common Mistakes
- Include
<algorithm>before using algorithms such asstd::sort,std::find, orstd::count_if. - Remember that algorithm ranges stop before the second iterator.
- Check the result of
std::find()before dereferencing it. - Know whether an algorithm changes the container or only reads from it.
Takeaway: STL algorithms let you express common operations clearly by applying well-tested functions to iterator ranges.
