博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ STL常用算法-66-算数算法-accumulate和fill
阅读量:4301 次
发布时间:2019-05-27

本文共 1351 字,大约阅读时间需要 4 分钟。

这篇来学习两个数学算法算法,这两个算法在头文件numeric中,属于小众算法,其实我们大部分使用的算法都包含在头文件algorithm中。

算法简介

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

fill      //向容器中添加元素

 

1.accumulate 

作用:计算区间内元素的总和

函数原型:accumulate(iterator beg, iterator end, value);

参数解释:参数3是一个起始叠加值,一般设置为0.

#include 
#include
#include
#include
using namespace std;void test01(){ vector
v; for(int i=0; i <=100; i++) { v.push_back(i); } // accumulate, 累计容器内元素求和算法 int total = accumulate(v.begin(), v.end(), 0); cout << "Total = " << total << endl; // 参数3,起止累加值为100 int total2 = accumulate(v.begin(), v.end(), 100); cout << "Total2 = " << total2 << endl;}int main(){ test01(); system("pause"); return 0;}

代码运行结果:

 

2.fill 算法

作用:fill英文单词是填充的意思,这个算法是指定区间内的元素填充为想要的数据,例如下面参数3 value

函数原型:fill(iterator beg, iterator end, value);

#include 
#include
#include
#include
#include
using namespace std;void Print01(int val){ cout << val << " ";}void test01(){ vector
v; v.resize(10); //10个元素值默认是0 for_each(v.begin(), v.end(), Print01); cout << endl; // fill 填充元素,例如把0全部填充为100 fill(v.begin(), v.end(), 100); for_each(v.begin(), v.end(), Print01); cout << endl;}int main(){ test01(); system("pause"); return 0;}

代码运行结果:

 

转载地址:http://eexws.baihongyu.com/

你可能感兴趣的文章
HTTP协议
查看>>
HTTPS
查看>>
git add . git add -u git add -A区别
查看>>
apache下虚拟域名配置
查看>>
session和cookie区别与联系
查看>>
PHP 实现笛卡尔积
查看>>
Laravel中的$loop
查看>>
CentOS7 重置root密码
查看>>
Centos安装Python3
查看>>
PHP批量插入
查看>>
laravel连接sql server 2008
查看>>
Laravel 操作redis的各种数据类型
查看>>
Laravel框架学习笔记之任务调度(定时任务)
查看>>
laravel 定时任务秒级执行
查看>>
浅析 Laravel 官方文档推荐的 Nginx 配置
查看>>
Swagger在Laravel项目中的使用
查看>>
Laravel 的生命周期
查看>>
CentOS Docker 安装
查看>>
Nginx
查看>>
Navicat远程连接云主机数据库
查看>>