11.10. Computing a Dot Product

Problem

You have two containers of numbers that are the same length and you want to compute their dot product.

Solution

Example 11-19 shows how you can compute a dot product using the inner_product function from the <numeric> header.

Example 11-19. Computing the dot product

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

using namespace std;

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;
}

The program in Example 11-19 produces the following output:

the dot product of (1,2,3) and (4,6,8) is 40

Discussion

The dot product is a form of inner product known as the Euclidean Inner Product. The inner_product function is declared as follows:

template<class In, class In2, class T>
T inner_product(In first, In last, In2 first2, T init);

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);

The first form of inner_product sums the result of multiplying corresponding elements from two containers. The second form of the inner_product function allows you to supply your own pairwise operation and accumulation function. See Example 11-20 to see a sample implementation demonstrating how inner_product works.

Example 11-20. Sample implementation of inner_product()

template<class In, class In2, class T, class BinOp, class BinOp2> T inner_product(In first, In last, In2 ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.