C++ accumulate 函数模板
std::accumulate 是 C++ 标准库 <numeric> 中的一个函数模板,它的主要作用是对一个范围内的元素进行累积运算。
简单来说,它可以帮你把一系列数字加起来,或者执行其他你定义的二元运算。
如果求和结果丢失小数,先检查初始值的类型;0、0.0与0LL的区别见下文的可运行例子。
主要功能和用法
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 连接起来。
初始值0、0.0、0LL有什么区别
初始值不仅提供起点,也决定累加器类型。0 是 int,0.0 是 double,0LL 是 long long。容器中存放 double,并不会让以0初始化的累加器自动改成double;把最终结果赋给double变量,也不能补回中间丢掉的小数。
例如 [0.6, 0.6]:以0初始化时,每一步都把相加结果重新赋给int累加器,两次都截去小数,结果为0;以0.0初始化则保留浮点累加,结果接近1.2。下面的图描述赋值过程,不是浮点精度基准。
0 + 0.6 → 赋给int:0
0 + 0.6 → 赋给int:0
0.0 + 0.6 → 约0.6
0.6 + 0.6 → 约1.2
将下面代码保存为accumulate_type.cpp,可用 clang++ -std=c++17 accumulate_type.cpp -o accumulate_type 编译并运行;不要加-DNDEBUG,以保留断言。示例按C++17编译执行过:验证整数初始值导致的小数丢失、浮点初始值、long long累加,以及空范围返回init。浮点结果用误差范围检查;不执行有符号整数溢出的表达式。
#include <cassert>
#include <cmath>
#include <numeric>
#include <vector>
int main() {
const std::vector<double> values{0.6, 0.6};
const auto wrong = std::accumulate(values.begin(), values.end(), 0);
const double too_late = std::accumulate(values.begin(), values.end(), 0);
const auto right = std::accumulate(values.begin(), values.end(), 0.0);
assert(wrong == 0);
assert(too_late == 0.0);
assert(std::abs(right - 1.2) < 1e-12);
const std::vector<long long> large{2'000'000'000LL, 1'000'000'000LL};
const auto wide = std::accumulate(large.begin(), large.end(), 0LL);
assert(wide == 3'000'000'000LL);
const std::vector<double> empty;
assert(std::accumulate(empty.begin(), empty.end(), 2.5) == 2.5);
}
整数总和需要更大范围时,可以选择0LL,但long long也有上限;自定义运算中的更窄中间表达式仍须单独检查。乘积通常从1或1LL开始,不能为了扩大类型把乘法初始值写成0。空范围不进行运算,直接返回给定的初始值。
依据:C++17工作草案N4659 [accumulate] 的逐项累加定义。相关边界见有符号整数溢出。
总结
std::accumulate 是一个强大且通用的算法,它简化了对一个序列中的元素进行累积计算的过程。通过指定初始值和可选的二元操作,你可以用它来执行各种各样的任务,而不仅仅是简单的求和。