Source of inner_product2a.cpp


  1: //inner_product2a.cpp

  3: #include <iostream>
  4: #include <vector>
  5: #include <numeric>
  6: #include <functional>
  7: using namespace std;

  9: int main()
 10: {
 11:     cout << "\nThis program illustrates the use of the STL "
 12:         "inner_product() algorithm\n(extended version) to compute the "
 13:         "inner product of two ranges of integer\nvalues from two "
 14:         "vectors of integers. This time multiplication is replaced\nby "
 15:         "addition and addition by multiplication, so that intead of the "
 16:         "\"usual\"\ninner product, which is the sum of products, we have "
 17:         "the product of sums.";
 18:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 20:     int a1[] = {2, 1, 4, 3};
 21:     vector<int> v1(a1, a1+4);

 23:     cout << "\nHere are the contents of v1:\n";
 24:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 25:         cout << v1.at(i) << " ";
 26:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 28:     int a2[] = {1, 2, 3, 4, 5, 6};
 29:     vector<int> v2(a2, a2+6);

 31:     cout << "\nHere are the contents of v2:\n";
 32:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 33:         cout << v2.at(i) << " ";
 34:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 36:     cout << "\nThe inner product (product of sums, in this case) of "
 37:         "the values in v1\nwith the values starting at the beginning "
 38:         "of v2 is "
 39:         << inner_product(v1.begin(), v1.end(), v2.begin(), 1,
 40:         multiplies<int>(), plus<int>()) << ".";
 41:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 43:     cout << "\nThe inner product (product of sums, in this case) of "
 44:         "the last three values\nof each vector is "
 45:         << inner_product(v1.end()-3, v1.end(), v2.end()-3, 1,
 46:         multiplies<int>(), plus<int>()) << ".";
 47:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 48: }