C++ accumulate()函数的用法

Posted on 2022-03-05 22:57  foghorn  阅读(919)  评论(0编辑  收藏  举报

accumulate定义在 numeric 中,作用有两个,一个是累加求和,另一个是自定义类型数据的处理。

头文件

#include <numeric>

原型

默认求累加和

template <class InputIterator, class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
  while (first!=last) {
    init = init + *first;  // or: init=binary_op(init,*first) for the binary_op version
    ++first;
  }
  return init;
}

自定义数据的处理

template <class InputIterator, class T, class BinaryOperation>
T accumulate (InputIterator first, InputIterator last, T init, BinaryOperation binary_op);

参数

  • first,last:迭代器,指向要操作的序列的区间[first, last)。first指向的元素参与计算,last不参与计算;
  • init:初始值,如在init的基础上进行求和计算;
  • binary_op:Binary operation taking an element of type T as first argument and an element in the range as second, and which returns a value that can be assigned to type T. This can either be a function pointer or a function object. The operation shall not modify the elements passed as its arguments.

案例

// accumulate example
#include <iostream>     // std::cout
#include <functional>   // std::minus
#include <numeric>      // std::accumulate

int myfunction (int x, int y) {return x+2*y;}
struct myclass {
	int operator()(int x, int y) {return x+3*y;}
} myobject;

int main () {
  int init = 100;
  int numbers[] = {10,20,30};

  std::cout << "using default accumulate: ";
  std::cout << std::accumulate(numbers,numbers+3,init);
  std::cout << '\n';

  std::cout << "using functional's minus: ";
  std::cout << std::accumulate (numbers, numbers+3, init, std::minus<int>());
  std::cout << '\n';

  std::cout << "using custom function: ";
  std::cout << std::accumulate (numbers, numbers+3, init, myfunction);
  std::cout << '\n';

  std::cout << "using custom object: ";
  std::cout << std::accumulate (numbers, numbers+3, init, myobject);
  std::cout << '\n';

  return 0;
}

输出:

using default accumulate: 160
using functional's minus: 40
using custom function: 220
using custom object: 280

Copyright © 2024 foghorn
Powered by .NET 9.0 on Kubernetes