常用算术生成算法
注意:
算术生成算法属于小型计算,使用包含头文件为#include<numeric>
算法简介:
- accumulate //计算容器元素累计总和
- fill //向容器中添加元素
函数原型:
- accumulate(iterator beg , iterator end,value);
- //计算容器元素累计总和
- //beg开始迭代器
- //end结束迭代器
- //value填充的值
示例:
#include<iostream>
using namespace std;
#include<numeric>
#include<vector>
void test01()
{
vector<int>v;
for (int i = 0;i <= 100;i++)
{
v.push_back(i);
}
int total = accumulate(v.begin(), v.end(), 0);
cout << "total = " << total <<endl;
}
int main()
{
test01();
system("pause");
return 0;
}
函数原型:
- fill(iterator beg , iterator end , value);
- //想容器中填充元素
- //beg开始迭代器
- //end结束迭代器
- //value填充的值
示例:
#include<iostream>
using namespace std;
#include<numeric>
#include<vector>
#include<algorithm>
void MyPrint(int val)
{
cout << val << " ";
}
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;
}