Function Objects

By default, the accumulate() function applies operator+ to all the elements residing in a container and returns the cumulative result of adding all the elements. In the case of an integer collection, if the initial value provided to accumulate() is 0, the result would be the sum of the collection. The accumulate() algorithm is by no means limited to object addition. It is capable of applying any operation to the container elements (given that the operation is supported by the elements) and returning the cumulative result [MS96]:

template <class InputIterator, class T>
T accumulate(InputIterator first,
             InputIterator beyondLast,
             T initialValue)
{
    while (first != beyondLast) {
          initialValue = initialValue + *first++;
          }
}

In C programming, ...

Get Efficient C++ Performance Programming Techniques 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.