(C++) std::partial\_sum
January 10, 2018 · View on GitHub
(C++) std::partial_sum
std::partial_sum is an STL algorithm to calculate the partial sums of a container.
#include <algorithm> #include <cassert> #include <numeric> #include <vector> int main() { //Create a std::vector with five ones const std::vector<int> v(5,1); assert(v[0] == 1); assert(v[1] == 1); assert(v[2] == 1); assert(v[3] == 1); assert(v[4] == 1); //Create a std::vector with the partial sums of five ones std::vector<int> w; std::partial_sum(v.begin(),v.end(),std::back_inserter(w)); assert(w[0] == 1); // 1 assert(w[1] == 2); // 1 + 1 assert(w[2] == 3); // 1 + 1 + 1 assert(w[3] == 4); // 1 + 1 + 1 + 1 assert(w[4] == 5); // 1 + 1 + 1 + 1 + 1 //Create a std::vector with the partial sums of //the partial sums of those five ones std::vector<int> x; std::partial_sum(w.begin(),w.end(),std::back_inserter(x)); assert(x[0] == 1); // 1 assert(x[1] == 3); // 1 + 2 assert(x[2] == 6); // 1 + 2 + 3 assert(x[3] == 10); // 1 + 2 + 3 + 4 assert(x[4] == 15); // 1 + 2 + 3 + 4 + 5 }