Computing a Dot Product


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


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


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



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

T inner_product(In first, In last, In2 first2, T init);

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

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

Building C++ Applications

Code Organization


Strings and Text

Dates and Times

Managing Data with Containers



Exceptions and Safety

Streams and Files

Science and Mathematics






C++ Cookbook
Secure Programming Cookbook for C and C++: Recipes for Cryptography, Authentication, Input Validation & More
ISBN: 0596003943
EAN: 2147483647
Year: 2006
Pages: 241 © 2008-2020.
If you may any questions please contact us: