函式模板
<numeric>

std::accumulate

sum (1)
template <class InputIterator, class T>   T accumulate (InputIterator first, InputIterator last, T init);
自定義 (2)
template <class InputIterator, class T, class BinaryOperation>   T accumulate (InputIterator first, InputIterator last, T init,                 BinaryOperation binary_op);
累加範圍中的值
返回將範圍 [first,last) 中所有值累加到 init 的結果。

預設操作是加法,但也可以指定其他操作作為 binary_op

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
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;
}

引數

first, last
輸入迭代器,指向序列的起始和結束位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
init
累加器的初始值。
binary_op
二元操作,接受一個型別為 T 的元素作為第一個引數,以及範圍中的一個元素作為第二個引數,並返回一個可以賦給型別 T 的值。
這可以是指向函式的指標,也可以是函式物件。
該操作不應修改作為其引數傳遞的元素。

返回值

累加 init 和範圍 [first,last) 中所有元素的結果。

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// 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


複雜度

線性的,與 firstlast 之間的 距離 成比例。

資料競爭

範圍 [first,last) 中的元素被訪問(每個元素被訪問一次)。

異常

如果 binary_op、賦值或迭代器上的操作丟擲異常,則本函式也丟擲異常。
請注意,無效引數會導致未定義行為

另見