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

C++StlVector

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

Actually there are quite a few methods.

int sum_of_elems = 0;

C++03

  1. Classic for loop:

     for(std::vector<int>::iterator it = vector.begin(); it != vector.end(); ++it)
         sum_of_elems += *it;
    
  2. Using a standard algorithm:

     #include <numeric>
    
     sum_of_elems = std::accumulate(vector.begin(), vector.end(), 0);
    

    Important Note: The last argument's type is used not just for the initial value, but for the type of the result as well. If you put an int there, it will accumulate ints even if the vector has float. If you are summing floating-point numbers, change 0 to 0.0 or 0.0f (thanks to nneonneo). See also the C++11 solution below.

C++11 and higher

  1. b. Automatically keeping track of the vector type even in case of future changes:

     #include <numeric>
    
     sum_of_elems = std::accumulate(vector.begin(), vector.end(),
                                    decltype(vector)::value_type(0));
    
  2. Using std::for_each:

     std::for_each(vector.begin(), vector.end(), [&] (int n) {
         sum_of_elems += n;
     });
    
  3. Using a range-based for loop (thanks to Roger Pate):

     for (auto& n : vector)
         sum_of_elems += n;
    

Solution 2 - C++

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

#include <numeric>
cout << accumulate(A.begin(), A.end(), 0);

Solution 3 - C++

Prasoon has already offered up a host of different (and good) ways to do this, none of which need repeating here. I'd like to suggest an alternative approach for speed however.

If you're going to be doing this quite a bit, you may want to consider "sub-classing" your vector so that a sum of elements is maintained separately (not actually sub-classing vector which is iffy due to the lack of a virtual destructor - I'm talking more of a class that contains the sum and a vector within it, has-a rather than is-a, and provides the vector-like methods).

For an empty vector, the sum is set to zero. On every insertion to the vector, add the element being inserted to the sum. On every deletion, subtract it. Basically, anything that can change the underlying vector is intercepted to ensure the sum is kept consistent.

That way, you have a very efficient O(1) method for "calculating" the sum at any point in time (just return the sum currently calculated). Insertion and deletion will take slightly longer as you adjust the total and you should take this performance hit into consideration.

Vectors where the sum is needed more often than the vector is changed are the ones likely to benefit from this scheme, since the cost of calculating the sum is amortised over all accesses. Obviously, if you only need the sum every hour and the vector is changing three thousand times a second, it won't be suitable.

Something like this would suffice:

class UberVector:
    private Vector<int> vec
    private int sum

    public UberVector():
        vec = new Vector<int>()
        sum = 0

    public getSum():
        return sum

    public add (int val):
        rc = vec.add (val)
        if rc == OK:
            sum = sum + val
        return rc

    public delindex (int idx):
        val = 0
        if idx >= 0 and idx < vec.size:
            val = vec[idx]
        rc =  vec.delindex (idx)
        if rc == OK:
            sum = sum - val
        return rc

Obviously, that's pseudo-code and you may want to have a little more functionality, but it shows the basic concept.

Solution 4 - C++

Why perform the summation forwards when you can do it backwards? Given:

std::vector<int> v;     // vector to be summed
int sum_of_elements(0); // result of the summation

We can use subscripting, counting backwards:

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v[i-1];

We can use range-checked "subscripting," counting backwards (just in case):

for (int i(v.size()); i > 0; --i)
    sum_of_elements += v.at(i-1);

We can use reverse iterators in a for loop:

for(std::vector<int>::const_reverse_iterator i(v.rbegin()); i != v.rend(); ++i)
    sum_of_elements += *i;

We can use forward iterators, iterating backwards, in a for loop (oooh, tricky!):

for(std::vector<int>::const_iterator i(v.end()); i != v.begin(); --i)
    sum_of_elements += *(i - 1);

We can use accumulate with reverse iterators:

sum_of_elems = std::accumulate(v.rbegin(), v.rend(), 0);

We can use for_each with a lambda expression using reverse iterators:

std::for_each(v.rbegin(), v.rend(), [&](int n) { sum_of_elements += n; });

So, as you can see, there are just as many ways to sum the vector backwards as there are to sum the vector forwards, and some of these are much more exciting and offer far greater opportunity for off-by-one errors.

Solution 5 - C++

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);

Solution 6 - C++

One can also use std::valarray<T> like this

#include<iostream>
#include<vector>
#include<valarray>

int main()
{
	std::vector<int> seq{ 1,2,3,4,5,6,7,8,9,10 };
	std::valarray<int> seq_add{ seq.data(), seq.size() };
	std::cout << "sum = " << seq_add.sum() << "\n";

	return 0;
}

Some may not find this way efficient since the size of valarray needs to be as big as the size of the vector and initializing valarray will also take time.

In that case, don't use it and take it as yet another way of summing up the sequence.

Solution 7 - C++

C++0x only:

vector<int> v; // and fill with data
int sum {}; // or = 0 ... :)
for (int n : v) sum += n;

This is similar to the BOOST_FOREACH mentioned elsewhere and has the same benefit of clarity in more complex situations, compared to stateful functors used with accumulate or for_each.

Solution 8 - C++

I'm a Perl user, an a game we have is to find every different ways to increment a variable... that's not really different here. The answer to how many ways to find the sum of the elements of a vector in C++ is probably an infinity...

My 2 cents:

Using BOOST_FOREACH, to get free of the ugly iterator syntax:

sum = 0;
BOOST_FOREACH(int & x, myvector){
  sum += x;
}

iterating on indices (really easy to read).

int i, sum = 0;
for (i=0; i<myvector.size(); i++){
  sum += myvector[i];
}

This other one is destructive, accessing vector like a stack:

while (!myvector.empty()){
   sum+=myvector.back();
   myvector.pop_back();
}

Solution 9 - C++

 #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);
    }

Solution 10 - C++

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.

Solution 11 - C++

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<>.

Solution 12 - C++

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.

Solution 13 - C++

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; 

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionPrasoon SauravView Question on Stackoverflow
Solution 1 - C++Prasoon SauravView Answer on Stackoverflow
Solution 2 - C++beahackerView Answer on Stackoverflow
Solution 3 - C++paxdiabloView Answer on Stackoverflow
Solution 4 - C++James McNellisView Answer on Stackoverflow
Solution 5 - C++rafakView Answer on Stackoverflow
Solution 6 - C++NeutronStarView Answer on Stackoverflow
Solution 7 - C++Roger PateView Answer on Stackoverflow
Solution 8 - C++krissView Answer on Stackoverflow
Solution 9 - C++hey dudeView Answer on Stackoverflow
Solution 10 - C++Pavan ChandakaView Answer on Stackoverflow
Solution 11 - C++Dhruv KakadiyaView Answer on Stackoverflow
Solution 12 - C++OGCJNView Answer on Stackoverflow
Solution 13 - C++Haresh karnanView Answer on Stackoverflow