You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 11:06:03