Lesson content
Read, practise, then check your understanding
Algorithms operate on iterator ranges rather than owning containers. This separation lets one implementation work with arrays, vectors, lists, and custom ranges when their iterator capabilities satisfy the operation.
#include <algorithm>
#include <numeric>
#include <vector>
std::vector<int> values{5, 1, 4, 1, 3};
std::sort(values.begin(), values.end());
auto newEnd = std::remove(values.begin(), values.end(), 1);
values.erase(newEnd, values.end());
int total = std::accumulate(values.begin(), values.end(), 0);
std::remove moves retained elements and returns a new logical end; it does not resize the container. C++20’s std::erase/std::erase_if simplify common removal.
Predicates and transformations
Use find, find_if, count_if, all_of, any_of, and none_of for queries. transform maps values, copy_if filters, and for_each performs an action. Sorting requires random-access iterators; list supplies its own sort. Binary search algorithms require a range already ordered by a compatible comparator.
A comparator must establish strict weak ordering; returning left <= right is wrong because an element would compare before itself. Prefer pure predicates with explicit captures. <ranges> algorithms accept ranges directly and projections can select a member without a custom lambda. Know complexity: sorting is O(n log n), linear search O(n), and binary search O(log n) comparisons on a suitable range. Named algorithms make intent reviewable and often enable library optimization.
Knowledge check
Answer every question correctly to complete this chapter.
0 of 10 checks passed
Your progress is saved on this device.