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.
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 first
s and return the second
s unchanged.
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
精彩评论