partial_sum()

Creates a new sequence in which, by default, the value of each new element represents the sum of all the previous elements up to its position. For example, given the sequence {0,1,1,2,3,5,8}, the new sequence is {0,1,2,4,7,12,20}. The fourth element, for example, is the partial sum of the three previous values (0,1,1) plus its own (2), yielding a value of 4. An optional fourth parameter allows the user to specify an alternative operation to apply.

 #include <numeric> int ires[7], ia[7] = { 1, 3, 4, 5, 7, 8, 9 }; vector<int> vres(7), vec( ia, ia+7 ); // partial_sum(): 1 4 8 13 20 28 37 partial_sum( ia, ia+7, ires ); //partial sum using times<int>(): 1 3 12 60 420 3360 30240 partial_sum(vec.begin(),vec.end(),vres.begin(),times<int>()); ...

Get Essential C++ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.