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

在 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: 15

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

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

taciturn丶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值