C++ <numeric>库accumulate方法内使用Lambda函数的参数匹配报错问题
错误原因
std::accumulate 传入的自定义二元操作函数需要遵循固定的参数规则:
- 第一个参数是上一轮累加后的结果,类型和你传入的初始值类型完全一致,这里你初始值传的是
0(int类型),所以第一个参数必须是int类型 - 第二个参数才是当前遍历到的容器元素,也就是你二维vector里的子元素
std::vector<int>类型
你写的lambda两个参数都声明成了std::vector<int>,编译器找不到int转vector的方法,自然就报错了。
修正方法
把lambda的第一个参数改为int类型,累加逻辑调整为「上一轮的累加结果 + 当前子vector的第一个元素」即可,修正后的完整代码如下:
#include <iostream> #include <vector> #include <numeric> int main() { std::vector< std::vector<int> > contests = {{5, 1}, {2, 1}, {1, 1}, {8, 1}, {10, 0}, {5, 0}}; int sum = std::accumulate(contests.begin(),contests.end(), 0, [](int acc, const std::vector<int>& cur)->int {return acc + cur[0];} ); std::cout << sum << std::endl; // 输出结果为31 return 0; }
内容的提问来源于stack exchange,提问作者Giogre
相关产品推荐
相关产品推荐

