Skip to content

Chapter 25 of 31

STL Algorithms

Express transformations, searches, sorting, accumulation, predicates, and ranges clearly.

42 minutes 10 quick checksBy Subha Prasad
Lesson 25 of 31Course navigation

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.

Which algorithm sorts a random-access range?
What does std::find return when no value matches?
Which algorithm applies an operation to each input and writes results?
What does the erase-remove idiom accomplish?
Why prefer standard algorithms?
Which algorithm combines a range into one value?
What does std::remove actually do?
Which algorithm tests whether every element satisfies a predicate?
What must a sort comparator provide?
What do C++20 ranges reduce?

0 of 10 checks passed

Your progress is saved on this device.