How to calculate the cumulative sum for a vector of doubles in C++?

Wawel100 picture Wawel100 · Jul 20, 2010 · Viewed 18.4k times · Source

I have a vector of doubles and I need to create another array which is a cumulative sum of the elements of the first. For example;

 vector<double> Array(10,1);
 vector<double> Sum(10);  

 Sum[0] = Array[0]; 
 for(unsigned int i=1; i<Array.size(); i++)
     Sum[i] = Sum[i-1] + Array[i]; 

Is there an in-built function that will perform the above cumulative sum?

Answer

Pontus Gagge picture Pontus Gagge · Jul 20, 2010

Without having tested it, something like

std::partial_sum(Array.begin(), Array.end(), Sum.begin(), plus<double>());

should do the trick, if it's C++. (Actually, the plus<double>() can be defaulted out, it seems.)