在 C++ 标准库中,泛型算法的“只读算法”指那些 不会改变它们所操作的容器中的元素,仅用于访问或获取信息的算法,例如查找、计数、遍历等操作。
accumulate
std::accumulate()是 C++ 标准库**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:累积的初始值。
○ op:二元操作函数(可选,默认为加法)。
-
基本实例:累加求和
#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: " << sum << std::endl; // 输出 Sum: 15return 0;
}
-
自定义操作:累乘
#include <vector>
#include <numeric>int main() {std::vector<int> nums = {2, 3, 4};// 初始值为 1,使用乘法操作int product = std::accumulate(nums.begin(), nums.end(), 1, [](int a, int b) { return a * b; });std::cout << "Product: " << product << std::endl; // 输出 Product: 24return 0;
}
-
自定义操作:字符串连接
#include <vector>
#include <string>
#include <numeric>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; });std::cout << sentence << std::endl; // 输出 Hello World!return 0;
}
-
常见错误
std::vector<double> vals = {1.5, 2.5, 3.5};// 错误!初始值 0 是 int 类型,结果会被截断为 int
double sum = std::accumulate(vals.begin(), vals.end(), 0); // 正确:初始值应为 0.0(double 类型)
double correct_sum = std::accumulate(vals.begin(), vals.end(), 0.0);
std::vector<int> empty_vec;// 危险!若容器为空,直接使用 begin() 和 end() 会导致未定义行为
int sum = std::accumulate(empty_vec.begin(), empty_vec.end(), 0); // 结果为 0(安全)// 但更安全的做法是检查容器是否为空
if (!empty_vec.empty()) {sum = std::accumulate(empty_vec.begin(), empty_vec.end(), 0);
}
-
进阶用法:自定义对象累积
struct Point {double 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; });std::cout << "Total: (" << total.x << ", " << total.y << ")" << std::endl;// 输出 Total: (9, 12)return 0;
}
-
总结
用途:std::accumulate 是一个灵活的算法,适用于求和、求积、字符串拼接、对象合并等场景。
性能:时间复杂度为 O(n),是线性操作。
注意:始终确保初始值类型与操作逻辑匹配,避免迭代器越界