I'm looking for a function in C++, to return the summation over all elements of an array, similar to what we have in Matlab, i.e., sum(A), where A is an array. I know one can simply do a for loop, but isn't there any function doing so, for example in "std::"?
The function is called std::accumulate
, and resides in <numeric>
.
It works with both Standard Library containers (which are able to provide an InputIterator
, so pretty much every one of them) and C-style arrays - provided you use std::begin
and std::end
. Otherwise container.begin()/end()
are of course fine; refer to the example use for more information.
One thing to note that it is provided with two overloads, one of them adding a BinaryOperation
. It defaults to std::plus
in the other version. What this means in practice is that it becomes a fold
or reduce
from other languages.
An example using C-style arrays, provided by @BoBTFish - ideone link.
#include <iostream>
#include <iterator>
#include <numeric>
int main()
{
int nums[] = {1,5,3,2,7,8,100,3};
std::cout
<< std::accumulate(std::begin(nums),
std::end(nums),
0)
<< '\n';
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With