STL Algorithms & Ranges¶
The C++ Standard Library provides a comprehensive suite of algorithms in the <algorithm> and <numeric> headers. By decoupling data storage (containers) from data manipulation (algorithms) via iterators, the STL allows you to write highly optimized, reusable logic that is often faster and less bug-prone than manual loops.
1. Non-Modifying Algorithms¶
These algorithms inspect a range of elements without modifying their values.
1. Searching: std::find and std::find_if¶
std::find searches for a specific value. std::find_if searches for an element satisfying a boolean predicate (such as a lambda expression).
2. Verification: std::all_of, std::any_of, std::none_of¶
These inspect if all, any, or none of the elements in a range satisfy a condition.
2. Modifying Sequence Algorithms¶
These algorithms copy, move, replace, or transform elements in a range.
1. Element Mapping: std::transform¶
Applies a function to all elements in a input range and stores the result in a destination range (which can be the same container).
2. In-Place Modifications: std::replace_if and std::fill¶
std::fillsets all elements to a uniform value.std::replace_ifreplaces elements satisfying a condition.
3. Sorting and Binary Search¶
C++ algorithms are highly optimized. std::sort typically uses Introsort (a hybrid of Quicksort, Heapsort, and Insertion Sort) with a complexity of $O(n \log n)$.
4. Numeric Algorithms (<numeric>)¶
These algorithms focus on arithmetic operations over ranges.
std::accumulate: Sums up a range (or accumulates values using a custom binary operation).std::reduce(C++17): Similar tostd::accumulate, but supports parallel execution because it does not guarantee left-to-right evaluation order.
5. Modern C++20 Ranges and Views¶
C++20 introduced the Ranges Library, which completely modernizes how algorithms are used in three ways:
- No Iterator Boilerplate: You can pass the entire container directly instead of
vec.begin(), vec.end(). - Piping Syntax (
|): Allows you to chain operations like filter and map in a readable pipeline. - Lazy Evaluation (Views): Operations are evaluated only when the elements are iterated over. No temporary vectors or duplicate allocations are created in memory, yielding zero memory overhead.
Related Guides¶
- STL Containers — The containers that hold the data for these algorithms.
- Functions — Lambdas and callables configuration.