7

I want a partial_sum of my elements in a vector, where each element is a pair<double, unsinged int>. The partial_sum should incrementally add the double values (first of each pair).

Example:

vector<pair<double, unsigned int> > temp_vec;
temp_vec.push_back(make_pair(0.5, 0));
temp_vec.push_back(make_pair(0.2, 1));
temp_vec.push_back(make_pair(0.3, 2));
partial_sum(temp_vec.begin(), temp_vec.end(), temp_vec.begin(), ???);   // in place

should give me a vector containing: [(0.5, 0), (0.7, 1), (1.0, 2)]

How to implement the necessary functor to use the partial_sum function?

I was able to use my pair in a stl lower_bound search with a custom-functor, but in the case above, I don't know how to declare the binary operation.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
sascha
  • 32,238
  • 6
  • 68
  • 110

2 Answers2

5
struct pair_sum {
    pair<double, unsigned int> operator()(const pair<double, unsigned int> & sum, const pair<double, unsigned int> & i) {
        return pair<double, unsigned int>(sum.first + i.first, i.second);
    }
};

This will add up the firsts and return the seconds unchanged.

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
  • Excellent. After converting your code to a functor with operator(), it perfectly worked. Exactly what i wanted to achieve. Just one remark: Your code is a "normal" function. Why didn't you post the functor? Is there any reason? (i'm kind of a c++ noob compared to the people around here; maybe i'm mixing up the terms) – sascha Nov 06 '10 at 16:02
  • @sascha: You are right, this is not a functor, I was just too lazy to type it all out. Will fix. – Björn Pollex Nov 06 '10 at 16:03
3

Here is a slight cleanup of https://stackoverflow.com/a/4113820/895245 with C++ lambdas, typedefs, and a runnable test:

#include <functional>
#include <iostream>
#include <numeric>
#include <vector>

int main() {
    typedef std::pair<double, int> P;
    auto v = std::vector<P> {
        {0.5, 0},
        {0.2, 1},
        {0.3, 2}
    };
    std::partial_sum(v.begin(), v.end(), v.begin(),
        [](const P& x, const P& y){return P(x.first + y.first, y.second);}
    );
    for (auto &x : v) {
        std::cout << x.first << " " << x.second << std::endl;
    }
}

Output:

0.5 0
0.7 1
1 2

If you also want to easily calculate the cumulative probability values from each probability, have a look at: Running Part of Code with a Specified Probability

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985