C++ STL常用算法-66-算数算法-accumulate和fill

阳光穿透心脏的1/2处 2022-11-30 05:42 203阅读 0赞

这篇来学习两个数学算法算法,这两个算法在头文件numeric中,属于小众算法,其实我们大部分使用的算法都包含在头文件algorithm中。

算法简介

accumulate //计算容器元素累计总和
fill //向容器中添加元素

1.accumulate

作用:计算区间内元素的总和

函数原型:accumulate(iterator beg, iterator end, value);

参数解释:参数3是一个起始叠加值,一般设置为0.

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <numeric>
  5. using namespace std;
  6. void test01()
  7. {
  8. vector<int> v;
  9. for(int i=0; i <=100; i++)
  10. {
  11. v.push_back(i);
  12. }
  13. // accumulate, 累计容器内元素求和算法
  14. int total = accumulate(v.begin(), v.end(), 0);
  15. cout << "Total = " << total << endl;
  16. // 参数3,起止累加值为100
  17. int total2 = accumulate(v.begin(), v.end(), 100);
  18. cout << "Total2 = " << total2 << endl;
  19. }
  20. int main()
  21. {
  22. test01();
  23. system("pause");
  24. return 0;
  25. }

代码运行结果:

20200823220834667.png

2.fill 算法

作用:fill英文单词是填充的意思,这个算法是指定区间内的元素填充为想要的数据,例如下面参数3 value

函数原型:fill(iterator beg, iterator end, value);

  1. #include <iostream>
  2. #include <string>
  3. #include <vector>
  4. #include <numeric>
  5. #include <algorithm>
  6. using namespace std;
  7. void Print01(int val)
  8. {
  9. cout << val << " ";
  10. }
  11. void test01()
  12. {
  13. vector<int> v;
  14. v.resize(10);
  15. //10个元素值默认是0
  16. for_each(v.begin(), v.end(), Print01);
  17. cout << endl;
  18. // fill 填充元素,例如把0全部填充为100
  19. fill(v.begin(), v.end(), 100);
  20. for_each(v.begin(), v.end(), Print01);
  21. cout << endl;
  22. }
  23. int main()
  24. {
  25. test01();
  26. system("pause");
  27. return 0;
  28. }

代码运行结果:

20200823221545248.png

发表评论

表情:
评论列表 (有 0 条评论,203人围观)

还没有评论,来说两句吧...

相关阅读