您的位置:首页 > 汽车 > 新车 > 推广软件哪个好_广告设计软件免费下载_百度seo排名曝光行者seo_seo信息优化

推广软件哪个好_广告设计软件免费下载_百度seo排名曝光行者seo_seo信息优化

2025/8/1 1:28:46 来源:https://blog.csdn.net/ever__ever/article/details/147309435  浏览:    关键词:推广软件哪个好_广告设计软件免费下载_百度seo排名曝光行者seo_seo信息优化
推广软件哪个好_广告设计软件免费下载_百度seo排名曝光行者seo_seo信息优化

在 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),是线性操作。
注意:始终确保初始值类型与操作逻辑匹配,避免迭代器越界

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com