算术生成算法属于小型算法,使用时包含头文件#include <numeric>
accumulate //计算容器中元素累计总和
fill //向容器中添加元素
(1)accumulate
计算区间内容器元素累计总和
函数原型:
accumulate(iterator beg,iterator end,value); //这里value表示容器区间内的值相加后再加上value值
示例:
//accumulate算法
void test01(){
vector<int>v;
for(int i=0;i<=100;i++){
v.push_back(i);
}
//从零开始相加到100
int total = accumulate(v.begin(),v.end(),1000);
cout<<"total = "<<total<<endl;
}
(2)fill
向容器中填充指定的元素
函数原型:
fill(iterator beg,iterator end,value);
示例:
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;
}