在地图上积累

Cla*_*nry 4 c++ algorithm dictionary accumulate

我无法编译这个相当简单的代码。我得到错误,could not deduce template argument for 'std::basic_string<_Elem,_Traits,_Alloc> &&' from 'int'。我是否需要通过一些自定义求和函数来累积?或者也许有更简单的方法来获得地图中所有第二个值的总和?谢谢!

#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;
}
Run Code Online (Sandbox Code Playgroud)

Vla*_*cow 6

对于 std::map 类型的容器,您不能以其简单形式使用算法 std::accuulate。您需要将算法与二元运算一起使用,并可能使用 lambda 表达式作为二元运算。例如

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