| Category: algorithms | Component type: function |
template <class InputIterator1
class InputIterator2
class T>
T inner_product(InputIterator1 first1
InputIterator1 last1
InputIterator2 first2
T init);
template <class InputIterator1
class InputIterator2
class T
class BinaryFunction1
class BinaryFunction2>
T inner_product(InputIterator1 first1
InputIterator1 last1
InputIterator2 first2
T init
BinaryFunction1 binary_op1
BinaryFunction2 binary_op2);
The first version of inner_product returns init plus the inner product of the two ranges [1]. That is it first initializes the result to init and then for each iterator i in [first1 last1) in order from the beginning to the end of the range updates the result by result = result + (*i) * *(first2 + (i - first1)).
The second version of inner_product is identical to the first except that it uses two user-supplied function objects instead of operator+ and operator*. That is it first initializes the result to init and then for each iterator i in [first1 last1) in order from the beginning to the end of the range updates the result by result = binary_op1(result binary_op2(*i *(first2 + (i - first1))). [2]
int main()
{
int A1[] = {1
2
3};
int A2[] = {4
1
-2};
const int N1 = sizeof(A1) / sizeof(int);
cout << "The inner product of A1 and A2 is "
<< inner_product(A1
A1 + N1
A2
0)
<< endl;
}
[1] There are several reasons why it is important that inner_product starts with the value init. One of the most basic is that this allows inner_product to have a well-defined result even if [first1 last1) is an empty range: if it is empty the return value is init. The ordinary inner product corresponds to setting init to 0.
[2] Neither binary operation is required to be either associative or commutative: the order of all operations is specified.