Compute dot product on two containers of numbers with the same length - C++ template

C++ examples for template:template function

Description

Compute dot product on two containers of numbers with the same length

Demo Code

#include <numeric>
#include <iostream>
#include <vector>

using namespace std;

template<class In, class In2, class T, class BinOp, class BinOp2>
T inner_product(In first, In last, In2 first2, T init, BinOp op, BinOp2 op2) {
  while (first != last) {
    BinOp(init, BinOp2(*first++, *first2++));
  }//from w ww.  j  a  v a2  s  . c o m
  return init;
}


int main() {
  int v1[] = { 1, 2, 3 };
  int v2[] = { 4, 6, 8 };
  cout << "the dot product of (1,2,3) and (4,6,8) is ";
  cout << inner_product(v1, v1 + 3, v2, 0) << endl;
}

Result


Related Tutorials