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

C++ STL常用算法之常用算术生成算法

常用算术生成算法

学习目标:

  • 掌握常用的算术生成算法

注意:

  • 算术生成算法属于小型算法,使用时包含的头文件为 #include <numeric>

算法简介:

  • accumulate // 计算容器元素累计总和

  • fill // 向容器中添加元素

accumulate

功能描述:

  • 计算区间内容器元素累计总和

函数原型:

  • accumulate(iterator beg, iterator end, value);

    • beg:开始迭代器

    • end:结束迭代器

    • value:起始值

#include <iostream>
#include <vector>
#include <numeric>

using namespace std;

int main() {
    // 创建一个包含多个元素的 vector
    vector<int> v = {1, 2, 3, 4, 5};

    // 输出容器的内容
    cout << "容器的内容: ";
    for (auto it = v.begin(); it != v.end(); it++) {
        cout << (*it) << " ";
    }
    cout << endl;

    // 计算容器元素的总和,起始值为 0
    int sum = accumulate(v.begin(), v.end(), 0);

    // 输出总和
    cout << "容器元素的总和: " << sum << endl;

    return 0;
}

fill

功能描述:

  • 向容器中填充指定的元素

函数原型:

  • fill(iterator beg, iterator end, value);

    • beg:开始迭代器

    • end:结束迭代器

    • value:填充的值

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main() {
    // 创建一个空的 vector 容器
    vector<int> v = {1,2,3,4,5};

    // 输出填充前的容器内容
    cout << "填充前的容器内容: ";
    for (auto it = v.begin(); it != v.end(); it++) {
        cout << (*it) << " ";
    }
    cout << endl;

    // 使用 fill 函数将容器中的元素全部填充为 10
    fill(v.begin(), v.end(), 10);

    // 输出填充后的容器内容
    cout << "填充后的容器内容: ";
    for (auto it = v.begin(); it != v.end(); it++) {
        cout << (*it) << " ";
    }
    cout << endl;

    return 0;
}

相关文章:

  • 【区块链安全 | 第十四篇】类型之值类型(一)
  • ShuffleNet、MobileNet 和 EfficientNet的区别
  • 探索OCR的第二个方案:EasyOCR
  • 小智机器人关键函数解析,Application::MainLoop() 用于持续监听事件组中的事件,并根据不同的事件触发相应的操作
  • Android在KSP中简单使用Room
  • Vue.js的多个组件过渡:实现组件的动态切换
  • 互联网的组成
  • C语言信号量使用案例
  • 每日小积累day1
  • TDengine tar.gz和docker两种方式安装和卸载
  • 【蓝桥杯速成】| 16.完全背包组合|排序
  • Rollup系列之安装和入门
  • MQTT之重复消息(6、在项目中遇到的问题)
  • Pandas **Series**
  • 传统策略梯度方法的弊端与PPO的改进:稳定性与样本效率的提升
  • 【干货】前端实现文件保存总结
  • rce操作
  • 唤起“堆”的回忆
  • 基于自定义注解+反射+AOP+Redis的通用开关设计:在投行交易与风控系统的落地实践
  • golang 的reflect包的常用方法