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 header.

Example 11-19. Computing the dot product

#include #include #include 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 T inner_product(In first, In last, In2 first2, T init); template 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 T inner_product(In first, In last, In2 first2, T init, BinOp op, Binop2 op2) { while (first != last) { BinOp(init, BinOp2(*first++, *first2++)); } return init; }

Because of its flexible implementation, you can use inner_product for many more purposes than just computing a dot product (e.g., you can use it to compute the distance between two vectors or compute the norm of a vector).

See Also

Recipe 11.11 and Recipe 11.12

Категории