std::accumulate的具体用法

本是古典 何须时尚 2022-11-03 01:37 255阅读 0赞

文章目录

  • std :: accumulate
    • 头文件
    • 原型
    • 参数
    • 返回值
    • 用例1
    • 用例2:Lambda表达式

std :: accumulate

作用累加求和,对于字符串可以将其连接起来(string类型的加,相当于字符串连接)

头文件

  1. #include <numeric>

原型

  1. accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

参数

  • first,last:
    将迭代器输入到序列中的初始位置和最终位置。使用的范围是[first,last),它包含所有的元件第一和最后一个,包括由指向的元件第一但不被指向的元素最后。
  • init
    累加器的初始值。
  • binary_op
    自定义数据类型, accumulate提供了回调函数(第四个参数),来实现自定义数据的处理。

返回值

累积 init 和范围内所有元素的结果 [first,last)。

用例1

在这里插入图片描述

  1. #include <iostream> // std::cout
  2. #include <numeric> // std::accumulate
  3. #include <functional> // std::minus
  4. int myfunction(int x, int y)
  5. {
  6. return 2 * x + y;
  7. }
  8. int main() {
  9. int init = 100;
  10. int numbers[] = { 10,20,30 };
  11. std::cout << "使用默认 accumulate: ";
  12. std::cout << std::accumulate(numbers, numbers + 3, init);
  13. std::cout << '\n';
  14. std::cout << "使用自定义 custom function accumulate: ";
  15. std::cout << std::accumulate(numbers, numbers + 3, init, myfunction);
  16. std::cout << '\n';
  17. return 0;
  18. }

用例2:Lambda表达式

  1. #include <iostream>
  2. #include <numeric>
  3. #include <vector>
  4. #include <string>
  5. #include <functional>
  6. int main()
  7. {
  8. std::vector<int> v{ 5,2,1,1,3,1,4 };
  9. std::string s = std::accumulate(
  10. std::next(v.begin()),
  11. v.end(),
  12. std::to_string(v[0]),
  13. [](std::string a, int b) {
  14. return a + '-' + std::to_string(b);
  15. });
  16. // 5-2-1-1-3-1-4
  17. std::cout << s << std::endl;
  18. return 0;
  19. }

发表评论

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

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

相关阅读