#define_CRT_SECURE_NO_WARNINGS#include<iostream>#include<vector>#include<numeric>
using namespace std;voidtest01(){
vector<int>v;for(int i =0; i <=100; i++){
v.push_back(i);}/*第三个参数为累加的起始值,如果没有特殊需求写0即可*/int total =accumulate(v.begin(), v.end(),0);
cout <<"容器中元素相加的和: "<< total << endl;return;}intmain(){test01();return0;}
运行结果
2. fill()
fill()函数向容器填充指定元素;
需要注意包含头文件#include<numeric>
代码工程
#define_CRT_SECURE_NO_WARNINGS#include<iostream>#include<vector>#include<numeric>#include<algorithm>
using namespace std;
class print
{
public:voidoperator()(int val){
cout << val <<" ";}};voidtest01(){
vector<int>v;
v.resize(10);/*将容器中填满10个元素,每个元素都是100*/fill(v.begin(), v.end(),100);for_each(v.begin(), v.end(),print());
cout << endl;return;}intmain(){test01();return0;}