C ++: what functions give the sum of an array?

I am looking for a function in C ++ to return a 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 that you can just make a for loop, but is there any function, for example, in "std ::"?

+4
source share
1 answer

The function is called std::accumulateand located in <numeric>.

It works with both standard library containers (which InputIteratoralmost every one of them can provide ) and C-style arrays if you use std::beginand std::end. Otherwise container.begin()/end(), of course, good; refer to usage example for more information.

One remark is that it is equipped with two overloads, one of which adds BinaryOperation. By default, it is equal std::plusin another version. In practice, this means that it becomes foldor reducefrom other languages.


An example of using C-style arrays provided by @BoBTFish is 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';
}
+12
source

All Articles