For a map like std::map, how do I accumulate it's values' sum?
Actually, I made it with a functor and std::for_each algorithm. But I'd also like to make this using std::accumulate algorithm.
I have no idea how to apply it to std::map.
Is this even 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;
}