Listing 98 accumulate_example.cpp
#include <iostream>
#include <numeric>
#include <vector>
int main() {
std::vector<int> vec{10, -1, -50, 101, 4, 2, 800, -250, 277, 8, 12};
auto sum = std::accumulate(vec.begin(), vec.end(), 0.0);
std::cout << "the sum is " << sum << std::endl;
auto prod = std::accumulate(vec.begin(), vec.end(), 1,
[] (const int& a, const int& b) {return a * b;});
std::cout << "the product is " << prod << std::endl;
}
std::accumulate usually takes 4 arguments:
An iterator pointing to the beginning of the range to sum
An iterator pointing to one-past the end of the range to sum
An initial value for the accumulation
A function to do the operation that takes two arguments. The
first is the current accumulated value and the second is an
element in the vector.
For our sum, we want to start with 0, and then we add to this.
With no operator as the 4th argument, std::accumulate will do a sum, so
that allows us to do this call:
auto sum = std::accumulate(vec.begin(), vec.end(), 0.0);
We could have used the C++ standard library std::plus function to be more explicit:
auto sum = std::accumulate(vec.begin(), vec.end(), std::plus<int>{});
or we could write our own (lambda) function and pass it in.
For our product, we want to start with 1, since multiplying the
first element by 1 will just give us the first element. In this
example, we write a lambda-function. We could also use std::multiplies.