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

如何用C++ STL库计算vector<int>中i*C[i]的求和?

用STL计算vector元素索引与元素的乘积之和

C++标准库中没有直接完成这个需求的算法,但可以通过std::accumulate结合自定义累加逻辑实现,这是最贴合STL风格的做法。

实现示例

#include <vector>
#include <numeric>

int main() {
    std::vector<int> C = {1, 2, 3, 4, 5};
    int sum = std::accumulate(C.begin(), C.end(), 0,
        [index = 0](int acc, int val) mutable {
            return acc + index++ * val;
        });
    // 计算结果:0*1 + 1*2 + 2*3 + 3*4 + 4*5 = 40
    return 0;
}

说明

  • std::accumulate负责遍历容器并执行累加操作,第三个参数是累加初始值(此处设为0)。
  • 自定义lambda表达式中,用可变的index变量跟踪当前元素的索引,每次累加时计算index * val并加到结果中,之后索引自增。
  • 如果担心int溢出,可以将初始值和返回类型替换为long long。

当然也可以手动遍历容器完成计算,但如果要求使用STL函数,std::accumulate是最优选择。

内容的提问来源于stack exchange,提问作者Subhankar Ghosal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 13:15:53