一、简述:
本人是因为在看力扣题的题解时正巧碰到了这个函数,而以前却没接触过该函数,故在此写一篇文章来当做笔记用。
在 C++ 中,std::accumulate
是一个用于对序列进行累积计算的算法,定义在 <numeric>
头文件中。它可以将一个范围内的元素按指定规则(默认是加法)逐步合并,最终返回一个累积结果。
二、函数原型:
#include <numeric> // 必须包含此头文件
template <class InputIt, class T>
T accumulate(InputIt first, InputIt last, T init);
template <class InputIt, class T, class BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op);
-
参数:
-
first
,last
: 输入范围的迭代器(左闭右开区间[first, last)
)。 -
init
: 初始值,类型为T
。 -
op
: 自定义的二元操作符(可选参数),用于替代默认的加法操作。
-
-
返回值:
-
返回最终的累积结果,类型与
init
相同。
-
三、基本用法:
1. 默认加法累积:
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
// 初始值为 0,累加所有元素
int sum = std::accumulate(nums.begin(), nums.end(), 0);
std::cout << sum; // 输出 15 (0+1+2+3+4+5)
return 0;
}
2. 自定义操作符(例如乘法) :
#include <iostream>
#include <vector>
#include <numeric>
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
// 初始值为 1,累乘所有元素
int product = std::accumulate(
nums.begin(), nums.end(),
1,
[](int a, int b) { return a * b; }
);
std::cout << product; // 输出 120 (1*1*2*3*4*5)
return 0;
}
四、关键点详解 :
1. 初始值 init
-
初始值的类型决定了最终结果的类型。
-
如果元素类型与
init
不同,会进行隐式类型转换。 -
示例:用
0.0
作为初始值计算浮点数和:
std::vector<int> nums = {1, 2, 3};
double sum = std::accumulate(nums.begin(), nums.end(), 0.0); // 结果为 6.0
2. 自定义二元操作符 op
-
op
是一个接受两个参数的函数(或函数对象、Lambda 表达式)。 -
参数顺序:第一个参数是累积值,第二个参数是当前元素。
-
示例:拼接字符串:
std::vector<std::string> words = {"Hello", " ", "World"};
std::string sentence = std::accumulate(
words.begin(), words.end(),
std::string(""), // 初始值为空字符串
[](const std::string& a, const std::string& b) { return a + b; }
);
// 输出 "Hello World"
3. 处理复杂数据类型
可以自定义操作符处理结构体或类:
struct Point {
int x, y;
Point operator+(const Point& other) const {
return {x + other.x, y + other.y};
}
};
int main() {
std::vector<Point> points = {
{1, 2}, {3, 4}, {5, 6}};
Point total = std::accumulate(
points.begin(), points.end(),
Point{0, 0}, // 初始值
[](const Point& a, const Point& b) { return a + b; }
);
// total = {9, 12}
return 0;
}
五、常见用途:
1.求和、求积:
std::vector<int> data = {10, 20, 30};
int total = std::accumulate(data.begin(), data.end(), 0);
2.字符串拼接:
std::vector<std::string> parts = {"A", "B", "C"};
std::string combined =
std::accumulate(parts.begin(), parts.end(), std::string(""));
六、注意事项:
-
初始值类型:确保
init
的类型与操作兼容(例如乘法时初始值应为 1,而非 0)。 -
操作符的结合性:
accumulate
是左结合的,操作顺序为((init op elem1) op elem2) op ...
。 -
迭代器有效性:确保迭代器范围
[first, last)
有效。