Algorithms library
A guide to Clause 26: algorithms touch data only through iterators and ranges; why one algorithm has classic, std::ranges and parallel overloads; which elements to look at when reading an algorithm's wording; and what each page of the clause covers.
Key points
- The algorithms of Clause 26 know nothing about containers; they read and write elements only through iterators (or C++20 ranges), so they work just as well on custom data structures.
- The same algorithm often has several groups of overloads: the classic
std::find, C++20'sstd::ranges::find, and parallel versions taking an execution policy as the first argument. - Classic versions express their requirements in the names of template parameters, and violating them is undefined behavior;
rangesversions express syntactic requirements as concept constraints, and violating them is a compile error. - Each algorithm's wording is laid out as Constraints, Mandates, Preconditions, Effects, Returns, Complexity. The complexity clauses are normative and often decide how many times a predicate is called.
Several forms of the same algorithm#
#include <algorithm>
#include <cassert>
#include <vector>
struct P { int id; };
int main() {
std::vector<int> v{4, 7, 1, 7};
auto a = std::find(v.begin(), v.end(), 7); // classic version
auto b = std::ranges::find(v, 7); // takes the whole range
std::vector<P> ps{{1}, {2}};
auto c = std::ranges::find(ps, 2, &P::id); // projection: compares p.id
assert(a == b && c == ps.begin() + 1);
}¶1 Clause 26 describes components for performing algorithmic operations on containers and other sequences. Algorithms never touch containers directly: find gets a pair of iterators, or a range, and knows only how to move iterators and read elements. So an algorithm written once works on arrays, vectors, linked lists, and any custom structure that provides suitable iterators ([algorithms.requirements]/1).
Open the synopsis of <algorithm> ([algorithm.syn]) and the same algorithm usually has four to six declarations. Taking find as the example:
| Form | Introduced | How requirements are expressed | On violation |
|---|---|---|---|
std::find(first, last, v) |
C++98, constexpr since C++20 |
template parameter name InputIterator |
UB |
std::find(std::execution::par, first, last, v) |
C++17 | parameter name ForwardIterator |
UB |
std::ranges::find(first, last, v, proj), std::ranges::find(r, v, proj) |
C++20 | concept constraints such as input_iterator |
compile error |
std::ranges::find(std::execution::par, r, v, proj) |
C++26 | random_access_iterator plus sized_sentinel_for |
compile error |
Some notes:
- The template parameters of the classic versions are unconstrained; names like
InputIteratorandForwardIteratorcarry normative meaning per [algorithms.requirements]/4. Passing an iterator that does not meet the requirements is not guaranteed to be diagnosed. - The
rangesversions write their requirements directly as constraints, and do not take part in overload resolution when they are not met. They generally have one extra projection (projection) parameter: before comparing or calling the predicate, the projection is applied to each element;&P::idabove is a projection. They are also not functions but objects, and ADL does not find them; see [algorithms.requirements]. - The parallel overloads take an execution policy as the first argument, are not
constexpr, and have stronger iterator requirements: the classic parallel versions need at least forward iterators, because splitting up the work needs multiple passes; C++26's parallelrangesversions (P3179R9) require the length to be computable in constant time and random access. See [algorithms.parallel].
Why the ranges algorithms are a separate set
C++20 Ranges (P0896R4) did not modify the classic algorithms; it added a new set in std::ranges. The classic algorithms require first and last to have the same type, have no projections, throw away some information they have already computed in their return values (std::copy does not return how far the input got), and can express their requirements only in prose. Changing the signatures directly would have broken existing code, so the two sets coexist.
Map of the clause#
¶2 The clause is divided into the groups below, per Table 85. Note that the headers are not all <algorithm>:
| Subclause | Header | Contents |
|---|---|---|
| [algorithms.requirements] | conventions for the whole clause: parameter names as requirements, the predicate contract, algorithm function objects | |
| [algorithms.parallel] | <execution> |
the semantics of parallel algorithms; execution policies themselves are in [execpol] |
| [algorithms.results] | <algorithm> |
return types of ranges algorithms, such as in_out_result |
| [alg.nonmodifying] | <algorithm> |
find, count, equal, search, fold_left and others |
| [alg.modifying.operations] | <algorithm> |
copy, transform, remove, unique, rotate, shuffle and others |
| [alg.sorting] | <algorithm> |
sorting, binary search, set operations, heaps, minimum and maximum |
| [numeric.ops] | <numeric> |
accumulate, reduce, the various scans |
| [specialized.algorithms] | <memory> |
uninitialized_copy, construct_at, destroy |
| [alg.rand] | <random> |
ranges::generate_random |
| [alg.c.library] | <cstdlib> |
qsort, bsearch |
Reading an algorithm's wording#
Most of the wording in this clause follows the same format ([structure.specifications]). It first defines a conditional expression with "Let E be …", so that the classic and ranges versions, and the versions with and without a predicate, share one description, and then lists in order:
| Element | Consequence of violation | Typical content |
|---|---|---|
| Constraints | does not take part in overload resolution | mostly in ranges versions |
| Mandates | ill-formed, diagnosis required | Size is convertible to an integral type; *first is writable to result |
| Preconditions | UB | ranges are valid, non-overlapping, already sorted; comp is a strict weak ordering |
| Effects, Returns | what it does, what it returns | |
| Complexity | the implementation does not conform | exactly N assignments; at most log₂N + O(1) comparisons |
| Remarks | whether it is stable ([algorithm.stable]), whether it can operate in place |
The complexity clauses are worth reading closely; they are often observable promises. std::count specifies exactly last - first applications of the predicate, std::find at most that many. So a predicate with side effects is called a definite number of times in count, while in find the number depends on where the element is found. adjacent_find specifies exactly min((i - first) + 1, (last - first) - 1) applications, and an implementation may not compare more to go faster.
Note that the ranges versions turn only the syntactic requirements into constraints. Semantic requirements, such as whether a comparison function really is a strict weak ordering, cannot be checked by the compiler, and violating them is still undefined behavior.
Algorithms in freestanding implementations#
The first comment in the synopsis is // mostly freestanding: freestanding implementations (those without operating system support, see [intro.compliance]) must also provide most of the algorithms in this clause. The few algorithms that may need to allocate a temporary buffer, such as stable_sort, stable_partition and inplace_merge, are marked // hosted and provided only in hosted implementations.
The parallel overloads are marked // freestanding-deleted. Per [freestanding.item]/3, a freestanding implementation may define such overloads as deleted or provide them as usual, at its choice. Defining them as deleted rather than omitting them ensures that the same call selects the same overload on both kinds of implementation.
Evolution#
| Version | Main changes |
|---|---|
| C++98 | STL algorithms adopted wholesale into the standard; sort required only O(N log N) on average |
| C++11 | sort required to be O(N log N) in the worst case; added all_of/any_of/none_of, is_sorted, minmax, move, shuffle and others |
| C++17 | parallel algorithms and execution policies (P0024R2); reduce and the scan family; sample, clamp |
| C++20 | most algorithms became constexpr; std::ranges algorithms (P0896R4); shift_left/shift_right |
| C++23 | ranges::fold_left and friends, ranges::contains, ranges::starts_with/ends_with, ranges::find_last |
| C++26 | stable_sort and others became constexpr (P2562R1); value arguments can be written as braced lists (P2248R8); parallel ranges overloads (P3179R9); algorithm function objects became customization point objects (P3136R1) |
Contents
- 26.1General[algorithms.general]
- 26.2Algorithms requirements[algorithms.requirements]done
- 26.3Parallel algorithms[algorithms.parallel]done
- 26.3.1Preamble[algorithms.parallel.defns]
- 26.3.2Requirements on user-provided function objects[algorithms.parallel.user]
- 26.3.3Effect of execution policies on algorithm execution[algorithms.parallel.exec]
- 26.3.4Parallel algorithm exceptions[algorithms.parallel.exceptions]
- 26.3.5Parallel algorithm overloads[algorithms.parallel.overloads]
- 26.3.6Execution policies[execpol]done
- 26.3.6.1General[execpol.general]
- 26.3.6.2Execution policy type trait[execpol.type]
- 26.3.6.3Sequenced execution policy[execpol.seq]
- 26.3.6.4Parallel execution policy[execpol.par]
- 26.3.6.5Parallel and unsequenced execution policy[execpol.parunseq]
- 26.3.6.6Unsequenced execution policy[execpol.unseq]
- 26.3.6.7Execution policy objects[execpol.objects]
- 26.4Header <algorithm> synopsis[algorithm.syn]
- 26.5Algorithm result types[algorithms.results]done
- 26.6Non-modifying sequence operations[alg.nonmodifying]done
- 26.6.1All of[alg.all.of]
- 26.6.2Any of[alg.any.of]
- 26.6.3None of[alg.none.of]
- 26.6.4Contains[alg.contains]
- 26.6.5For each[alg.foreach]
- 26.6.6Find[alg.find]
- 26.6.7Find last[alg.find.last]
- 26.6.8Find end[alg.find.end]
- 26.6.9Find first of[alg.find.first.of]
- 26.6.10Adjacent find[alg.adjacent.find]
- 26.6.11Count[alg.count]
- 26.6.12Mismatch[alg.mismatch]
- 26.6.13Equal[alg.equal]
- 26.6.14Is permutation[alg.is.permutation]
- 26.6.15Search[alg.search]
- 26.6.16Starts with[alg.starts.with]
- 26.6.17Ends with[alg.ends.with]
- 26.6.18Fold[alg.fold]
- 26.7Mutating sequence operations[alg.modifying.operations]done
- 26.7.1Copy[alg.copy]
- 26.7.2Move[alg.move]
- 26.7.3Swap[alg.swap]
- 26.7.4Transform[alg.transform]
- 26.7.5Replace[alg.replace]
- 26.7.6Fill[alg.fill]
- 26.7.7Generate[alg.generate]
- 26.7.8Remove[alg.remove]
- 26.7.9Unique[alg.unique]
- 26.7.10Reverse[alg.reverse]
- 26.7.11Rotate[alg.rotate]
- 26.7.12Sample[alg.random.sample]
- 26.7.13Shuffle[alg.random.shuffle]
- 26.7.14Shift[alg.shift]
- 26.8Sorting and related operations[alg.sorting]done
- 26.8.1General[alg.sorting.general]
- 26.8.2Sorting[alg.sort]
- 26.8.3Nth element[alg.nth.element]
- 26.8.4Binary search[alg.binary.search]done
- 26.8.5Partitions[alg.partitions]
- 26.8.6Merge[alg.merge]
- 26.8.7Set operations on sorted structures[alg.set.operations]done
- 26.8.8Heap operations[alg.heap.operations]done
- 26.8.9Minimum and maximum[alg.min.max]done
- 26.8.10Bounded value[alg.clamp]
- 26.8.11Lexicographical comparison[alg.lex.comparison]
- 26.8.12Three-way comparison algorithms[alg.three.way]
- 26.8.13Permutation generators[alg.permutation.generators]
- 26.9Header <numeric> synopsis[numeric.ops.overview]
- 26.10Generalized numeric operations[numeric.ops]done
- 26.10.1General[numeric.ops.general]
- 26.10.2Definitions[numerics.defns]
- 26.10.3Accumulate[accumulate]
- 26.10.4Reduce[reduce]
- 26.10.5Inner product[inner.product]
- 26.10.6Transform reduce[transform.reduce]
- 26.10.7Partial sum[partial.sum]
- 26.10.8Exclusive scan[exclusive.scan]
- 26.10.9Inclusive scan[inclusive.scan]
- 26.10.10Transform exclusive scan[transform.exclusive.scan]
- 26.10.11Transform inclusive scan[transform.inclusive.scan]
- 26.10.12Adjacent difference[adjacent.difference]
- 26.10.13Iota[numeric.iota]
- 26.10.14Greatest common divisor[numeric.ops.gcd]
- 26.10.15Least common multiple[numeric.ops.lcm]
- 26.10.16Midpoint[numeric.ops.midpoint]
- 26.10.17Saturation arithmetic[numeric.sat]done
- 26.11Specialized <memory> algorithms[specialized.algorithms]done
- 26.11.1General[specialized.algorithms.general]
- 26.11.2Special memory concepts[special.mem.concepts]
- 26.11.3uninitialized_default_construct[uninitialized.construct.default]
- 26.11.4uninitialized_value_construct[uninitialized.construct.value]
- 26.11.5uninitialized_copy[uninitialized.copy]
- 26.11.6uninitialized_move[uninitialized.move]
- 26.11.7uninitialized_fill[uninitialized.fill]
- 26.11.8construct_at[specialized.construct]
- 26.11.9destroy[specialized.destroy]
- 26.12Specialized <random> algorithms[alg.rand]draft
- 26.13C library algorithms[alg.c.library]done