注意:
- 算术生成算法属于小型算法,使用时包含的头文件为 #include <numeric>
算法简介:
- accumulate //计算容器元素累加总和
- fill //向容器中添加元素
1. accumulate
功能描述:
函数原型:
accumulate(iterator beg, iterator end, value);
- beg:开始迭代器
- end:结束迭代器
- value:起始值
代码示例:
#include<iostream>
using namespace std;
#include <numeric>
#include <vertor>
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();
return 0;
}
### total = 5050
#注意:这里填充的值为0,若填充1000,输出结果为6050
2.fill
功能描述:
函数原型:
fill(iterator beg; iterator end, value);
- beg:开始迭代器
- end:结束迭代器
- value:填充的值
代码示例:
#include<iostream>
using namespace std;
#include <numeric>
#include <vertor>
#include <algorithm>
void myPrint(int val)
{
cout << val << "";
}
void test01()
{
vector<int> v;
v.resize(10);
#默认是0,后期重新填充
fill(v.begin(), v.end(), 100);
for_each(e.begin(), e.end(), myPrint);
cout << endl;
}
int main() {
test01();
return 0;
}
# 100 100 100 100 100 100 100 100 100 100