本文共 1351 字,大约阅读时间需要 4 分钟。
这篇来学习两个数学算法算法,这两个算法在头文件numeric中,属于小众算法,其实我们大部分使用的算法都包含在头文件algorithm中。
算法简介
accumulate //计算容器元素累计总和
fill //向容器中添加元素
1.accumulate
作用:计算区间内元素的总和
函数原型:accumulate(iterator beg, iterator end, value);
参数解释:参数3是一个起始叠加值,一般设置为0.
#include#include #include #include using namespace std;void test01(){ vector v; for(int i=0; i <=100; i++) { v.push_back(i); } // accumulate, 累计容器内元素求和算法 int total = accumulate(v.begin(), v.end(), 0); cout << "Total = " << total << endl; // 参数3,起止累加值为100 int total2 = accumulate(v.begin(), v.end(), 100); cout << "Total2 = " << total2 << endl;}int main(){ test01(); system("pause"); return 0;}
代码运行结果:
2.fill 算法
作用:fill英文单词是填充的意思,这个算法是指定区间内的元素填充为想要的数据,例如下面参数3 value
函数原型:fill(iterator beg, iterator end, value);
#include#include #include #include #include using namespace std;void Print01(int val){ cout << val << " ";}void test01(){ vector v; v.resize(10); //10个元素值默认是0 for_each(v.begin(), v.end(), Print01); cout << endl; // fill 填充元素,例如把0全部填充为100 fill(v.begin(), v.end(), 100); for_each(v.begin(), v.end(), Print01); cout << endl;}int main(){ test01(); system("pause"); return 0;}
代码运行结果:
转载地址:http://eexws.baihongyu.com/