在C++编程中,计算数组所有元素的和是基础且高频的操作,除了传统的手写循环遍历累加之外,标准库中的std::accumulate函数提供了更简洁的实现方式,该函数定义在<numeric>头文件中,支持多种数值累加场景。

std::accumulate基本用法
std::accumulate的最基础用法是计算数组或容器中所有元素的和,它接收三个必填参数:起始迭代器、结束迭代器、初始累加值。初始累加值决定了返回值的类型,也作为累加的起始值。
下面是一个计算普通数组和的示例:
#include <iostream>
#include <numeric> // 包含std::accumulate的头文件
#include <vector>
int main() {
int arr[] = {1, 2, 3, 4, 5};
// 计算数组arr的和,初始累加值为0
int sum1 = std::accumulate(arr, arr + 5, 0);
std::cout << "数组和:" << sum1 << std::endl; // 输出 15
std::vector<int> vec = {10, 20, 30, 40};
// 计算vector容器元素的和
int sum2 = std::accumulate(vec.begin(), vec.end(), 0);
std::cout << "vector和:" << sum2 << std::endl; // 输出 100
return 0;
}
std::accumulate的进阶技巧
1. 自定义累加规则
std::accumulate还支持传入第四个参数,即自定义的操作函数,实现非默认的累加逻辑,比如计算数组元素的乘积、拼接字符串等。
#include <iostream>
#include <numeric>
#include <vector>
#include <string>
// 自定义乘积函数
int multiply(int a, int b) {
return a * b;
}
int main() {
std::vector<int> nums = {1, 2, 3, 4};
// 计算所有元素的乘积,初始值为1
int product = std::accumulate(nums.begin(), nums.end(), 1, multiply);
std::cout << "乘积结果:" << product << std::endl; // 输出 24
std::vector<std::string> strs = {"Hello", " ", "World", "!"};
// 拼接字符串,初始值为空字符串
std::string result = std::accumulate(strs.begin(), strs.end(), std::string(""));
std::cout << "拼接结果:" << result << std::endl; // 输出 Hello World!
return 0;
}
2. 处理自定义类型数据
如果数组或容器中存放的是自定义结构体或类对象,也可以通过自定义操作函数实现累加,比如计算自定义对象的某个属性总和。
#include <iostream>
#include <numeric>
#include <vector>
struct Student {
std::string name;
int score;
};
// 自定义累加函数,计算所有学生的分数总和
int sum_score(int total, const Student& stu) {
return total + stu.score;
}
int main() {
std::vector<Student> students = {
{"张三", 85},
{"李四", 92},
{"王五", 78}
};
// 初始累加值为0,传入自定义累加函数
int total_score = std::accumulate(students.begin(), students.end(), 0, sum_score);
std::cout << "总分:" << total_score << std::endl; // 输出 255
return 0;
}
注意事项
- 初始累加值的类型会影响最终结果的类型,比如初始值设为0是int类型,结果就是int,如果设为0.0就是double类型,避免类型截断问题。
- std::accumulate的迭代器范围是左闭右开区间,和容器的begin、end规则一致,不要写错范围导致漏算或多算元素。
- 自定义操作函数的参数顺序固定,第一个参数是当前的累加结果,第二个参数是当前遍历到的元素,不要写反顺序。
与手写循环的对比
手写循环实现数组求和的代码示例如下:
#include <iostream>
#include <vector>
int main() {
int arr[] = {1, 2, 3, 4, 5};
int sum = 0;
for (int i = 0; i < 5; i++) {
sum += arr[i];
}
std::cout << "数组和:" << sum << std::endl; // 输出 15
return 0;
}
对比可见,std::accumulate的代码更简洁,减少了循环变量的定义和控制逻辑,可读性更高,同时标准库的实现经过了充分测试,可靠性更强。不过如果需要复杂的遍历逻辑,比如遍历过程中需要判断、跳过元素,手写循环会更灵活。
C++std::accumulate数组求和数值算法修改时间:2026-06-15 12:06:31