How to apply std :: accumulate algorithm for associative containers?

For a map like std :: map, how do I summarize it? In fact, I did this with a functor and std :: for_each. But I would also like to do this using the std :: accumulate algorithm.
I do not know how to apply it to std :: map.
Is it possible?

struct Accumurator : std::unary_function<std::pair<int, int>, void> { Accumurator() : totalValue_(0) { } void operator()(const std::pair<int, int>& p) { totalValue_ += p.second; } int result() const { return totalValue_; } int totalValue_; }; int _tmain(int argc, _TCHAR* argv[]) { std::map<int, int> m; m.insert(make_pair(1, 10)); m.insert(make_pair(2, 10)); m.insert(make_pair(3, 10)); m.insert(make_pair(4, 10)); m.insert(make_pair(5, 10)); m.insert(make_pair(6, 10)); int totalSum = std::for_each(m.begin(), m.end(), Accumurator()).result(); // How can I apply accumulate algorithm for associative containers. // int totalSum = accumulate(m.begin(), m.end(), ???); return 0; } 
+4
source share
2 answers

Nearly. The functor must be a binary operator that takes the return type as the first and the range type as the second argument:

 x = Functor(init, *it++); x = Functor(x, *it++); x = Functor(x, *it++); // ... until it == end 

Thus, you do not need a full-fledged functor, a simple function will do:

 int map_acc(int lhs, const std::pair<int, int> & rhs) { return lhs + rhs.second; } const int sum = std::accumulate(m.begin(), m.end(), 0, map_acc); 
+6
source

std :: accumulate requires an init argument and a binary operation to be performed. Your binary operation should take a pair as the second argument, and int as the first argument and return int.

 struct pair_add { int operator()(int i, const std::pair<int, int>& x) { return i + x.second; } }; //use as int totalSum = accumulate(m.begin(), m.end(), 0, pair_add()); 

The real problem is getting the functor as general as possible.

+2
source

All Articles