C++ accumulate 函数模板
std::accumulate 是 C++ 标准库 <numeric> 中的一个函数模板,它的主要作用是对一个范围内的元素进行累积运算。
简单来说,它可以帮你把一系列数字加起来,或者执行其他你定义的二元运算。
主要功能和用法
std::accumulate 通常用于:
- 求和: 这是最常见的用途,计算一个容器(如 std::vector, std::list 等)中所有元素的总和。
- 其他累积运算: 你可以提供自定义的二元操作函数,例如计算元素的乘积、连接字符串,或者执行更复杂的累积逻辑。
函数原型
std::accumulate 有两个主要的原型:
- 使用默认的加法运算:
template <class InputIt, class T>
T accumulate(InputIt first, InputIt last, T init);
first, last: 输入迭代器,定义了要进行累积操作的元素范围 [first, last)。
init: 累积的初始值。这个值的类型 T 决定了累积结果的类型,并且累积操作会从这个初始值开始。
- 使用自定义的二元运算:
template <class InputIt, class T, class BinaryOperation>
T accumulate(InputIt first, InputIt last, T init, BinaryOperation op);
- first, last, init: 与前一个版本相同。
- op: 一个二元操作函数(或函数对象,例如 lambda 表达式),它接受两个参数(第一个是当前的累积值,第二个是范围中的当前元素)并返回新的累积值。
示例
1. 计算整数向量的总和
#include <vector>
#include <numeric> // 需要包含 <numeric> 头文件
#include <iostream>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
int sum = std::accumulate(numbers.begin(), numbers.end(), 0);
// sum 将会是 1 + 2 + 3 + 4 + 5 = 15
std::cout << "Sum: " << sum << std::endl; // 输出: Sum: 15
return 0;
}
在这个例子中:
- numbers.begin() 和 numbers.end() 定义了 numbers 向量中的所有元素。
- 0 是初始值。累积从 0 开始,然后依次加上向量中的每个元素。
2. 计算整数向量的乘积
#include <vector>
#include <numeric>
#include <iostream>
#include <functional> // 为了 std::multiplies
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
long long product = std::accumulate(numbers.begin(), numbers.end(), 1LL, std::multiplies<long long>());
// product 将会是 1 * 2 * 3 * 4 * 5 = 120
// 注意: 初始值设为 1LL (long long 类型的 1) 以避免溢出,并且运算也使用 long long
std::cout << "Product: " << product << std::endl; // 输出: Product: 120
return 0;
}
在这个例子中:
- 初始值是 1LL (long long类型的1),因为乘以0会得到0。
- std::multiplies<long long>() 是一个函数对象,它执行乘法操作。
3. 使用 Lambda 表达式进行自定义操作 (例如,连接字符串)
#include <vector>
#include <string>
#include <numeric>
#include <iostream>
int main() {
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;
});
// sentence 将会是 "Hello World!"
std::cout << "Sentence: " << sentence << std::endl; // 输出: Sentence: Hello World!
return 0;
}
在这个例子中:
- 初始值是一个空字符串 std::string(“”)。
- Lambda 表达式 [](const std::string& a, const std::string& b) { return a + b; } 定义了如何将当前的累积字符串 a 和向量中的下一个字符串 b 连接起来。
总结
std::accumulate 是一个强大且通用的算法,它简化了对一个序列中的元素进行累积计算的过程。通过指定初始值和可选的二元操作,你可以用它来执行各种各样的任务,而不仅仅是简单的求和。