Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How calculate sum of values in std::vector<int> [duplicate]

Tags:

c++

Possible Duplicate:
sum of elements in a std::vector

I have std::vector<int> and I want to calculate the sum of all the values in that vector. Is there any built in function or I need to write my custom code?

like image 951
Jame Avatar asked Jul 19 '11 06:07

Jame


People also ask

How do you sum a vector in C++?

Sum up of all elements of a C++ vector can be very easily done by std::accumulate method. It is defined in <numeric> header. It accumulates all the values present specified in the vector to the specified sum.

How do you sum values in vectors?

Description. S = sum( A ) returns the sum of the elements of A along the first array dimension whose size does not equal 1. If A is a vector, then sum(A) returns the sum of the elements. If A is a matrix, then sum(A) returns a row vector containing the sum of each column.

Which function can be used to find the sum of the vector container?

Which function can be used to find the sum of a vector container? Explanation: STL provides accumulate() function to find the sum of a vector.


2 Answers

Use the STL algorithm std::accumulate, in the numeric header.

#include <numeric>

    // ...
    std::vector<int> v;
    // ...
    int sum = std::accumulate(v.begin(), v.end(), 0);
like image 182
John Calsbeek Avatar answered Sep 21 '22 14:09

John Calsbeek


accumulate(v.begin(), v.end(), 0);

Look here for more details.

like image 39
Petar Minchev Avatar answered Sep 17 '22 14:09

Petar Minchev