C++ Numeric Library - inner_product


Advertisements

Description

It is used to compute cumulative inner product of range and returns the result of accumulating init with the inner products of the pairs formed by the elements of two ranges starting at first1 and first2.

Declaration

Following is the declaration for std::inner_product.

C++98

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 BinaryOperation1, class BinaryOperation2>
   T inner_product (InputIterator1 first1, InputIterator1 last1,
                    InputIterator2 first2, T init,
                    BinaryOperation1 binary_op1,
                    BinaryOperation2 binary_op2);

C++11

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 BinaryOperation1, class BinaryOperation2>
   T inner_product (InputIterator1 first1, InputIterator1 last1,
                    InputIterator2 first2, T init,
                    BinaryOperation1 binary_op1,
                    BinaryOperation2 binary_op2);
  • first, last − It iterators to the initial and final positions in a sequence.

  • init − It is an initial value for the accumulator.

  • binary_op − It is binary operation.

  • binary_op2 − It is binary operation and taking two elements.

Return Value

It returns the result of accumulating init and the products of all the pairs of elements in the ranges starting at first1 and first2.

Exceptions

It throws if any of the operations on the elements or iterators throws.

Data races

The elements in the range [first1,last1) are accessed.

Example

In below example for std::adjacent_difference.

#include <iostream>
#include <functional>
#include <numeric>

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[] = {20,30,40};
   int series2[] = {1,2,3};

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

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

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

   return 0;
}

The output should be like this −

Default inner_product: 300
Functional operations: 52
Ccustom functions: 4
numeric.htm
Advertisements