Introduction
The STL does not only contain data structures but also algorithms, of course. While data structures help store and maintain data in different ways with different motivations and targets, algorithms apply specific transformations to the data in such data structures.
Let's have a look at a standard task, such as summing up items from a vector. This can be done easily by looping over the vector and summing up all the items into an accumulator variable called sum
:
vector<int> v {100, 400, 200 /*, ... */ }; int sum {0}; for (int i : v) { sum += i; } cout << sum << '\n';
But because this is quite a standard task, there is also an STL algorithm for this:
cout << accumulate(begin(v), end(v), 0) << '\n';
In this case, the handcrafted loop variant is not much longer, and it is also not significantly harder to read than a one-liner which says what it does: accumulate
. In a lot of cases, however, it is awkward to read a 10-line code loop just to realize, ...