Pages

std::accumulate()

If you need to summarize values in a sequence, the standard function accumulate() is what are you looking for. It is a simple and useful function that just requires some attention. Firstly, its prototype is not in the algorithm include file, as one could expect, but in the less popular numeric. Secondly, we should remeber that the type of the resulting "accumulated" value is deducted by the function from the value we pass it as initial value.

So, if this is the container we are working with:

std::vector<double> vd;
vd.reserve(10);
for(int i = 0; i < 10; ++i)
vd.push_back(1.34 + i * 0.11);
dump(vd);

We'll write something like:

double sum = std::accumulate(vd.begin(), vd.end(), 0.0);
std::cout << "Sum is: " << sum << std::endl;

Where the stress is on the fact that the third parameter of accumulate() is 0.0, a double, and not 0, a simple int.

If we want to get the product of all the elements in the sequence, we use the overload of accumulate() that requires a predicate as last parameter, and we pass it an instance of the standard functor multiplies - in this case specifying double as underlying type:

double prod = std::accumulate(vd.begin(), vd.end(), 1.0, std::multiplies<double>());
std::cout << "Product is: " << prod << std::endl;

More info on std::accumulate(), and its (here not even mentioned) relation with for_each(), in Item 37 of Effective STL, one of the Effective C++ book series by Scott Meyers.

No comments:

Post a Comment