Source of replace_if1a.cpp


  1: //replace_if1a.cpp

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

  8: /**
  9: Determines if an integer is divisible by 3.
 10: Pre:\n n contains an integer.
 11: Post:\n Returns true if n is divisible by 3, and otherwise false.
 12: */
 13: bool isDivisibleByThree
 14: (
 15:     int n //in
 16: )
 17: {
 18:     return (n%3 == 0);
 19: }

 21: int main()
 22: {
 23:     cout << "\nThis program illustrates the use of the STL "
 24:         "replace_if() algorithm to\nreplace all copies of a given "
 25:         "value in a vector of integers that satisfy\na given "
 26:         "predicate with another value.";
 27:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

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

 37:     cout << "\nNow we replace all values divisble by 3 with 123.";
 38:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 39:     replace_if(v.begin(), v.end(), isDivisibleByThree, 123);

 41:     cout << "\nHere are the revised contents of the vector:\n";
 42:     for (vector<int>::size_type i=0; i<v.size(); i++)
 43:         cout << v.at(i) << " ";
 44:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 45: }