Source of accumulate2a.cpp


  1: //accumulate2a.cpp

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

  8: /**
  9: Finds the product of two integers.
 10: Pre:\n a and b contain integer values.
 11: Post:\n The product of a and b has been returned.
 12: */
 13: int product
 14: (
 15:     int a, //in
 16:     int b  //in
 17: )
 18: {
 19:     return a*b;
 20: }

 22: int main()
 23: {
 24:     cout << "\nThis program illustrates the use of the STL accumulate() "
 25:         "algorithm (expanded\nversion) from <numeric> to find the "
 26:         "product of integers in a vector, using a\nprogrammer-defined "
 27:         "function to compute the product of two integers.";
 28:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 30:     int a[] = {2, 4, 6, 8, 10};
 31:     vector<int> v(a, a+5);

 33:     cout << "\nHere are the integer values in the vector:\n";
 34:     for (vector<int>::size_type i=0; i<v.size(); i++)
 35:         cout << v.at(i) << " ";
 36:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 38:     cout << "\nThe product of these values is "
 39:         << accumulate(v.begin(), v.end(), 1, product) << ".";
 40:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 42:     cout << "\nThe product of the middle three values and an intial "
 43:         "value of -5 is "
 44:         << accumulate(v.begin()+1, v.end()-1, -5, product) << ". ";
 45:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 47:     cout << "\nThe product of the values in an empty range, with "
 48:         "an intial value of 22, is "
 49:         << accumulate(v.begin(), v.begin(), 22, product) << ".";
 50:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 51: }