Chapter Overview

Let's get an idea of what we'll cover in this chapter.

We'll cover the following...

Much of the power of the STL is in the standardization of container interfaces. If a container has a particular capability, there's a good chance that the interface for that capability is standardized across container types. This standardization makes possible a library of algorithms that operate seamlessly across containers and sequences sharing a common interface.


For example, if we want to sum all the elements in a vector of int, we could use a loop, or we could use an algorithm:

vector<int> x { 1, 2, 3, 4, 5 };
auto sum = accumulate(x.begin(), x.end(), 0); // sum is 15

This same syntax works with other containers:

deque<int> x { 1, 2, 3, 4, 5 };
auto sum = accumulate(x.begin(), x.end(), 0); // sum is 15

The algorithm version is not necessarily shorter , but it is easier to read and easier to maintain. And an algorithm is often more efficient than the equivalent loop.

Beginning with C++20, the ranges library provides a set of alternative algorithms that operate with ranges and views. This course will demonstrate those alternatives where appropriate. For more information on ranges and views, refer to the recipe Create Views into Containers with Ranges.


Most of the algorithms are in the algorithm header. Some numeric algorithms, notably accumulate(), are in the numeric header, and some memory-related algorithms A memory-related algorithm refers to a computational procedure designed to efficiently manage and manipulate data stored in computer memory during the execution of a program. are in the memory header.


We will cover STL algorithms in the following recipes:

  • Copy from one iterator to another
  • Join container elements into a string
  • Sort containers with std::sort
  • Modify containers with std::transform
  • Find items in a container
  • Limit the values of a container to a range with std::clamp
  • Sample data sets with std::sample
  • Generate permutations of data sequences
  • Merge sorted containers