Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accumulate on Map

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;
}
like image 366
ch-pub Avatar asked Feb 13 '23 20:02

ch-pub


2 Answers

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 ); } );
like image 51
Vlad from Moscow Avatar answered Feb 24 '23 12:02

Vlad from Moscow


Element type of std::map<K,V> is std::pair<const K,V> for which operator+ is not defined. You need to use 4 argument version of accumulate and supply your own addition operation:

typedef std::pair<int, int> Pair;

int sum = accumulate(m.begin(), m.end(), 0,
    [](int i, Pair p){ return i + p.second; }); 
like image 39
jrok Avatar answered Feb 24 '23 13:02

jrok