-
Book Overview & Buying
-
Table Of Contents
C++ STL Cookbook - Second Edition
By :
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 it possible for a library of algorithms to 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;
Or we could use an algorithm:
vector<int> x {1, 2, 3, 4, 5};
auto sum = accumulate(x.begin(), x.end(), 0);
This same syntax works with other containers:
deque<int> x {1, 2, 3, 4, 5};
auto sum = accumulate(x.begin(), x.end(), 0);
The algorithm version is easier to read and easier to maintain, and an algorithm is often more efficient than the equivalent loop.
Beginning with C++20, the...
Change the font size
Change margin width
Change background colour