当前位置: 首页 > news >正文

泛型算法——只读算法(一)

在 C++ 标准库中,泛型算法的“只读算法”指那些 不会改变它们所操作的容器中的元素,仅用于访问或获取信息的算法,例如查找、计数、遍历等操作。

accumulate

std::accumulate()是 C++ 标准库**numeric**头文件中提供的算法,用于对序列(如数组、容器等)进行累积计算。以下是其详细用法和常见场景:
  1. 函数原型
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:二元操作函数(可选,默认为加法)。

  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: " << sum << std::endl; // 输出 Sum: 15return 0;
}
  1. 自定义操作:累乘
#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;
}
  1. 自定义操作:字符串连接
#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;
}
  1. 常见错误
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);
}
  1. 进阶用法:自定义对象累积
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;
}
  1. 总结

用途std::accumulate 是一个灵活的算法,适用于求和、求积、字符串拼接、对象合并等场景。
性能:时间复杂度为 O(n),是线性操作。
注意:始终确保初始值类型与操作逻辑匹配,避免迭代器越界

相关文章:

  • Oracle 处理“不允许长度为0的列”(ORA-01723)问题解析
  • Oracle_00000
  • Spring Boot 学习总结(35)—— 使用 SpringAI 实现 MCP 服务并与 Qwen 集成使用?
  • 图形变换算法
  • 通过gird布局实现div的响应式分布排列
  • 生物信息学技能树(Bioinformatics)与学习路径
  • Ubuntu + VSCode 开发 STM32:用全开源工具,点亮你的第一盏 LED
  • 线性代数 | 知识点整理 Ref 3
  • AI在多Agent协同领域的核心概念、技术方法、应用场景及挑战 的详细解析
  • 【刷题Day18】HTTP状态码与请求(浅)
  • Leetcode 3359. 查找最大元素不超过 K 的有序子矩阵【Plus题】
  • dumpsys--音频服务状态信息
  • GUI GUIDIER8.2版本兼容8.3.1版本
  • SLAM | 激光SLAM中的退化问题
  • Linux系统中的Perf总结
  • LabVIEW 开发:永不落幕的求知之旅​
  • 【C++初阶】--- list容器功能模拟实现
  • 【AI】以Llama模型为例学习如何进行LLM模型微调
  • HttpSessionBindingListener 的用法笔记250417
  • 【LLM Prompt】CoT vs.ToT
  • 白玉兰奖征片综述丨海外剧创作趋势观察:跨界·融变·共生
  • 师爷、文士、畸人:会稽范啸风及其著述
  • 牛市早报|持续推进城市更新行动意见印发,证监会强化上市公司募资监管
  • 问责!美国海军对“杜鲁门”号航母一系列事故展开调查
  • 习近平会见智利总统博里奇
  • 孙卫东会见巴基斯坦驻华大使:支持巴印两国实现全面持久停火