Source of for_each1a.cpp


  1: //for_each1a.cpp

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

  8: //Note that for_each() requires a void function parameter.
  9: void DoCube(int& x) { x = x*x*x; }
 10: void DoDisplay(int& x) { cout << x << " "; }

 12: int main()
 13: {
 14:     cout << "\nThis program illustrates the use of the STL for_each() "
 15:         "algorithm to find\nthe cube of each value in a vector of "
 16:         "integers. We also use the for_each()\nalgorithm to display the "
 17:         "values in the vector.";
 18:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 20:     int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 21:     vector<int> v(a, a+10);

 23:     cout << "\nHere are the initial contents of v:\n";
 24:     for_each(v.begin(), v.end(), DoDisplay);
 25:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 27:     cout << "\nAnd here are the cubes of the values in v:\n";
 28:     for_each(v.begin(), v.end(), DoCube);
 29:     for_each(v.begin(), v.end(), DoDisplay);
 30:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 31: }