Chapter 6: STL Algorithms
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:
vector<int> x { 1, 2, 3, 4, 5 };
long sum{};
for( int i : x ) sum += i; // sum is 15
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: ...
Get C++20 STL Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.