Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++: which functions gives the sum of an array?

Tags:

c++

arrays

sum

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::"?

like image 536
yaro Avatar asked Dec 15 '22 16:12

yaro


1 Answers

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';
}
like image 85
Bartek Banachewicz Avatar answered Jan 03 '23 05:01

Bartek Banachewicz