C / C++ / 系统课时

用 accumulate 完成数据聚合

用 accumulate 完成数据聚合

当多个元素最终要合并成一个结果时,例如计算总和、累计金额或拼接字符串,可以使用 std::accumulate。它从一个初始值开始,按顺序把区间中的每个元素累积到同一个结果中。

学习目标

  • 使用 std::accumulate 计算数值总和
  • 理解初始值如何决定累加结果的类型
  • 通过自定义操作完成字符串等非数值聚合

accumulate 如何累计一个范围

std::accumulate 定义在 <numeric> 中。最常见的三个参数分别是起始迭代器、结束迭代器和初始值。默认操作等价于不断执行加法:先把初始值与第一个元素合并,再继续处理后续元素。

因此,对 {10, 20, 30, 40} 使用初始值 0,计算过程可以理解为 (((0 + 10) + 20) + 30) + 40,最终得到 100。

一个示例完成求和与字符串拼接

第四个参数可以提供自定义二元操作,因此 accumulate 并不限于数字。下面同时演示整数求和,以及通过 Lambda 把多个字符串拼接成逗号分隔的文本:

cpp
#include <iostream>
#include <numeric>
#include <string>
#include <vector>

int main() {
    std::vector<int> numbers{10, 20, 30, 40};
    const int total = std::accumulate(numbers.begin(), numbers.end(), 0);

    std::vector<std::string> words{"alpha", "beta", "gamma"};

    // 初始字符串为空;首次累计时不添加前导逗号。
    const std::string joined = std::accumulate(
        words.begin(), words.end(), std::string{},
        [](std::string result, const std::string& word) {
            if (!result.empty()) {
                result += ',';
            }
            result += word;
            return result;
        });

    std::cout << "total = " << total << '\n';
    std::cout << "joined = " << joined << '\n';
}

预期输出:

text
total = 100
joined = alpha,beta,gamma

初始值不仅决定起点

初始值还会影响累加器的类型。若元素是较大的整数,而初始值写成 0,累加器通常就是 int;即使最终把结果赋给 long long,中间计算也可能已经发生整数溢出。

需要宽整数累计时,应从一开始就提供正确类型,例如把初始值写成 0LL:

cpp
long long total = std::accumulate(numbers.begin(), numbers.end(), 0LL);

预期结果:累计过程使用 long long 保存中间结果,适合总和可能超出 int 表示范围的场景。

自定义操作需要满足累计关系

四参数版本的操作会接收“当前累计结果”和“当前元素”,并返回新的累计结果。它适合总和、乘积、文本拼接,以及把多个值逐步合成为一个对象。

对于字符串示例,累计器类型是 std::string,元素类型也是 std::string;其他场景中两者可以不同,只要自定义操作能够接收对应参数并返回可继续累计的结果。

std::accumulate 会按迭代器顺序线性处理范围,因此时间复杂度为 O(n)O(n)。当问题本质是“把一组元素归并成一个结果”时,它通常比手写累计循环更直接;其中最需要检查的不是算法本身,而是初始值类型和自定义操作是否准确表达了聚合规则。

按自己的节奏,确认真正理解。

目录与阅读设置

阅读设置

17

记录一个想法

用 accumulate 完成数据聚合

0 / 10000 · 笔记保存到账号。未提交的修改会在关闭、离开或刷新后丢失。

登录哪都通