19

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?

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
Wawel100
  • 1,221
  • 4
  • 21
  • 26
  • @Oded: It's most likely C++ with the std namespace included. Any Confirmation from Wawel? – Akusete Jul 20 '10 at 09:04
  • 1
    @Akusete - possibly, but could be any language that supports the `<>` generic syntax and has a C like structure (Java, C#, C++...) – Oded Jul 20 '10 at 09:05
  • 1
    I agree, its far from conclusive (+1), but given the use of lowercase vector and the surrounding constructor syntax its not a bad place to start until given more info. – Akusete Jul 20 '10 at 09:06
  • The tags say it's C++ ... so it's safe to say we are talking about C++ – Laurens Ruijtenberg Jul 20 '10 at 09:11
  • 1
    @Laurens: The C++ tag has been added by Pontus Gagge only after Akusete's comment. – Philipp Jul 20 '10 at 09:29

1 Answers1

39

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
  • 17,166
  • 1
  • 38
  • 51