views:

128

answers:

1

Hi,

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?

Thanks!

+7  A: 

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

Pontus Gagge
If you want to pass the binary operation explicitly, it must be `std::plus<double>()`.
Philipp
Thanks, I always misremember! Now, was that plus<double> ungood or what...? Probably summed to 1984, anyway! :-)
Pontus Gagge