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

算术生成算法属于小型算法,使用时包含头文件#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;
}
发布了31 篇原创文章 · 获赞 20 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/souhanben5159/article/details/104079524