函式模板
<numeric>

std::inner_product

sum/multiply (1)
template <class InputIterator1, class InputIterator2, class T>   T inner_product (InputIterator1 first1, InputIterator1 last1,                    InputIterator2 first2, T init);
自定義 (2)
template <class InputIterator1, class InputIterator2, class T,          class BinaryOperation1, class BinaryOperation2>   T inner_product (InputIterator1 first1, InputIterator1 last1,                    InputIterator2 first2, T init,                    BinaryOperation1 binary_op1,                    BinaryOperation2 binary_op2);
計算範圍的累積內積
返回將 init 與兩個範圍(從 first1first2 開始)的元素對的內積累加起來的結果。

預設的兩個操作(將乘積對累加)可以透過引數 binary_op1binary_op2 進行覆蓋。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
template <class InputIterator1, class InputIterator2, class T>
   T inner_product (InputIterator1 first1, InputIterator1 last1,
                    InputIterator2 first2, T init)
{
  while (first1!=last1) {
    init = init + (*first1)*(*first2);
               // or: init = binary_op1 (init, binary_op2(*first1,*first2));
    ++first1; ++first2;
  }
  return init;
}

引數

first1, last1
輸入迭代器 指向第一個序列的初始和末尾位置。使用的範圍是 [first1,last1),它包含 first1last1 之間的所有元素,包括 first1 指向的元素,但不包括 last1 指向的元素。
first2
輸入迭代器 指向第二個序列的初始位置。該範圍從 first2 開始,並且包含與上面範圍([first1,last1))相同數量的元素。
init
累加器的初始值。
binary_op1
二元操作,接受兩個型別為 T 的元素作為引數,並返回累加操作的結果。
這可以是一個函式指標或一個函式物件。
binary_op2
二元操作,接受兩個型別為 T 的元素作為引數,並返回內積操作的結果。
這可以是一個函式指標或一個函式物件。
兩個操作都不應修改其作為引數傳遞的任何元素。

返回值

累加 init 和來自 first1first2 開始的範圍內的所有元素對的乘積的結果。

示例

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
// inner_product example
#include <iostream>     // std::cout
#include <functional>   // std::minus, std::divides
#include <numeric>      // std::inner_product

int myaccumulator (int x, int y) {return x-y;}
int myproduct (int x, int y) {return x+y;}

int main () {
  int init = 100;
  int series1[] = {10,20,30};
  int series2[] = {1,2,3};

  std::cout << "using default inner_product: ";
  std::cout << std::inner_product(series1,series1+3,series2,init);
  std::cout << '\n';

  std::cout << "using functional operations: ";
  std::cout << std::inner_product(series1,series1+3,series2,init,
                                  std::minus<int>(),std::divides<int>());
  std::cout << '\n';

  std::cout << "using custom functions: ";
  std::cout << std::inner_product(series1,series1+3,series2,init,
                                  myaccumulator,myproduct);
  std::cout << '\n';

  return 0;
}

輸出

using default inner_product: 240
using functional operations: 70
using custom functions: 34


複雜度

線性時間複雜度,與 first1last1 之間的距離成比例。

資料競爭

兩個範圍內的元素都會被訪問(每個元素被訪問一次)。

異常

如果對元素或迭代器的任何操作丟擲異常,則此函式也丟擲異常。
請注意,無效引數會導致未定義行為

另見