Accumulate on Map

accumulate, algorithm, c++, dictionary

Solution

You may not use algorithm std::accuulate in its simple form for a container of type std::map. You need use the algorithm with binary operation and to use possibly a lambda expression as the binary operation. For example

int sum = accumulate( m.begin(), m.end(), 0,
                      []( int acc, std::pair<int, int> p ) { return ( acc + p.second ); } );

Problem

I can't get this rather simple code to compile. I get the error, `could not deduce template argument for 'std::basic_string<_Elem,_Traits,_Alloc> &&' from 'int'`. Do I need to pass some custom summing function to accumulate? Or perhaps is there a simpler way to get the sum of all second values in the map? Thanks! ``` #include <iostream> #include <math.h> #include <map> #include <numeric> int main() { map<int, int> m; m[1] = 1; m[2] = -1; m[3] = 1; m[4] = 2; int sum = accumulate(m.begin(), m.end(), 0); cout << sum; return 0; } ```

Original source