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

c++常用的算术生成算法

注意:

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

算法简介:

  • accumulate   //计算容器元素累加总和
  • fill                  //向容器中添加元素

1. accumulate

功能描述:
  • 计算区间内 容器元素累计总和
函数原型:
accumulate(iterator beg, iterator end, value);
  • beg:开始迭代器
  • end:结束迭代器
  • value:起始值 
代码示例:
#include<iostream>
using namespace std;
#include <numeric>
#include <vertor>

void test01()
{
    vector<int> v;
    for(int i = 0; i <=100; i++){
        v.push_back(i);
    }

    int total = accumulate(v.begin(), v.end(), 0);
    
    cout << "total = " << total << endl;
}

int main() {

    test01();
    return 0;
}    
    
### total = 5050
#注意:这里填充的值为0,若填充1000,输出结果为6050

2.fill

功能描述:
  • 向容器中填充指定的元素
函数原型:
fill(iterator beg; iterator end, value);
  • beg:开始迭代器
  • end:结束迭代器
  • value:填充的值
代码示例:
#include<iostream>
using namespace std;
#include <numeric>
#include <vertor>
#include <algorithm>

void myPrint(int val)
{
    cout << val << "";
}

void test01()
{
    vector<int> v;
    v.resize(10);
    
    #默认是0,后期重新填充
    fill(v.begin(), v.end(), 100);

    for_each(e.begin(), e.end(), myPrint);
    cout << endl;
}

int main() {

    test01();
    return 0;
}    
    
# 100 100 100 100 100 100 100 100 100 100


http://www.kler.cn/a/585767.html

相关文章:

  • Kotlin apply 方法的用法和使用场景
  • Windows10安装Rust 和ZED(失败)
  • 基于Python+MySQL编写的(WinForm)图书管理系统
  • C语言零基础入门:嵌入式系统开发之旅
  • CSS 的 inherit、initial、revert 和 unset区别
  • 工作记录 2017-01-12
  • package.json 依赖包约束及快速删除node_modules
  • 【实战ES】实战 Elasticsearch:快速上手与深度实践-8.2.2成本优化与冷热数据分离
  • c++介绍锁 一
  • ECU BootLoader开发——Flash编程
  • 【SpringMVC】入门版
  • 【CXX】6.8 Vec<T> — rust::Vec<T>
  • 渗透测试工具之Empire Framework
  • 交互式调度算法学不会?————一文学懂(RR(时间片轮转调度算法),优先级调度算法,多级反馈队列调度算法)保姆式解析
  • DPU的架构:模块化与可扩展性
  • MFC控件按钮的使用
  • 破局企业数据泄露风险:安当TDE透明加密重塑文件服务器安全防线
  • Flutter+Rust Android, IOS移动端适配通用流程及依赖库处理(Openssl, Curl等)
  • 百度百科更新!树莓集团宜宾项目的深远影响与意义
  • leetcode hot100贪心