5.5 常用算术生成算法
1、学习目标:
- 掌握常用的算术生成算法
2、注意:
- 算术生成算法属于小型算法,使用时包含头文件
3、算法简介: - accumulate //计算容器元素累计总和
- fill //向容器中添加元素
5.5.1 accumulate
1、功能描述:
- 计算区间内容器元素累计总和
2、函数原型:
- accumulate(iterator beg,iterator end,value);
- //计算容器元素累计总和
- //beg 开始迭代器
- //end 结束迭代器
- //起始值
3、代码
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
//常用算术生成算法
void test01()
{
vector<int>v;
for (int i = 0; i < 10; i++)
{
v.push_back(i);
}
//参数3,累加起始值
int sum=accumulate(v.begin(), v.end(), 0);
cout << sum << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
4、总结:
- accumulate使用时头文件注意是numeric,这个算法很实用
5、运行结果
5.5.2 fill
1、功能描述:
- 向容器中添加元素
2、 函数原型:
- accumulate(iterator beg,iterator end,value);
- //计算容器元素累计总和
- //beg 开始迭代器
- //end 结束迭代器
- //value 填充的值
3、代码
#include<iostream>
using namespace std;
#include<vector>
#include<numeric>
#include<algorithm>
void MyPrint(int val)
{
cout << val << " ";
}
//常用算术生成算法 fill
void test01()
{
vector<int>v;
v.resize(10);
//后期填充
fill(v.begin(), v.end(), 100);
for_each(v.begin(), v.end(), MyPrint);
cout << endl;
}
int main()
{
test01();
system("pause");
return 0;
}
4、总结:
- 利用fill算法可以将容器区间内的元素填充为指定的值
5、运行结果