How to sum up elements of a C++ vector?

Viewed 489012

What are the good ways of finding the sum of all the elements in a std::vector?

Suppose I have a vector std::vector<int> vector with a few elements in it. Now I want to find the sum of all the elements. What are the different ways for the same?

13 Answers

The easiest way is to use std:accumulate of a vector<int> A:

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);
 #include<iostream>
    #include<vector>
    #include<numeric>
    using namespace std;
    int main() {
       vector<int> v = {2,7,6,10};
       cout<<"Sum of all the elements are:"<<endl;
       cout<<accumulate(v.begin(),v.end(),0);
    }

Using inclusive_scan (C++17 and above):

The advantage is you can get sums of first "N" elements in a vector. Below is the code. Explanation in comments.

To use inclusive_scan , need to include "numeric" header.

    //INPUT VECTOR
    std::vector<int> data{ 3, 1, 4, 1, 5, 9, 2, 6 };

    //OUTPUT VECTOR WITH SUMS
    //FIRST ELEMENT - 3 
    //SECOND ELEMENT - 3 + 1 
    //THIRD ELEMENT - 3 + 1 + 4 
    //FOURTH ELEMENT - 3 + 1 + 4 + 1
    // ..
    // ..
    //LAST ELEMENT - 3 + 1 + 4 + 1 + 5 + 9 + 2 + 6
    std::vector<int> sums(data.size());

    //SUM ALL NUMBERS IN A GIVEN VECTOR.
    inclusive_scan(data.begin(), data.end(),
        sums.begin());

    //SUM OF FIRST 5 ELEMENTS.
    std::cout << "Sum of first 5 elements :: " << sums[4] << std::endl;

    //SUM OF ALL ELEMENTS
    std::cout << "Sum of all elements :: " << sums[data.size() - 1] << std::endl;

Also there is an overload where the execution policy can be specified. Sequential execution or Parallel execution. Need to include "execution" header.

    //SUM ALL NUMBERS IN A GIVEN VECTOR.
    inclusive_scan(std::execution::par,data.begin(), data.end(),
        sums.begin());

Using reduce :

One more option which I did not notice in the answers is using std::reduce which is introduced in c++17.

But you may notice many compilers not supporting it (Above GCC 10 may be good). But eventually the support will come.

With std::reduce, the advantage comes when using the execution policies. Specifying execution policy is optional. When the execution policy specified is std::execution::par, the algorithm may use hardware parallel processing capabilities. The gain may be more clear when using big size vectors.

Example:

//SAMPLE
std::vector<int> vec = {2,4,6,8,10,12,14,16,18};
    
//WITHOUT EXECUTION POLICY
int sum = std::reduce(vec.begin(),vec.end());
    
//TAKING THE ADVANTAGE OF EXECUTION POLICIES
int sum2 = std::reduce(std::execution::par,vec.begin(),vec.end());
    
std::cout << "Without execution policy  " << sum << std::endl;
std::cout << "With execution policy  " << sum2 << std::endl;

You need <numeric> header for std::reduce. And '<execution>' for execution policies.

std::accumulate could have overflow issues so the best approach could be to do range based accumulation on bigger data type variable to avoid overflow issues.

long long sum = 0;
for (const auto &n : vector)
  sum += n;

And then downcast to appropriate data type further using static_cast<>.

Nobody seems to address the case of summing elements of a vector that can have NaN values in it, e.g. numerical_limits<double>::quite_NaN()

I usually loop through the elements and bluntly check.

vector<double> x;

//...

size_t n = x.size();

double sum = 0;

for (size_t i = 0; i < n; i++){

  sum += (x[i] == x[i] ? x[i] : 0);

}

It's not fancy at all, i.e. no iterators or any other tricks but I this is how I do it. Some times if there are other things to do inside the loop and I want the code to be more readable I write

double val = x[i];

sum += (val == val ? val : 0);

//...

inside the loop and re-use val if needed.

It is easy. C++11 provides an easy way to sum up elements of a vector.

sum = 0; 
vector<int> vec = {1,2,3,4,5,....}
for(auto i:vec) 
   sum+=i;
cout<<" The sum is :: "<<sum<<endl; 
Related