Source of remove_if1a.cpp


  1: //remove_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 remove_if() "
 24:         "algorithm to\nremove all values that are divisible by 3 from "
 25:         "a vector of integers.";
 26:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

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

 38:     cout << "\nNow we remove all 5 values that are divisble by 3.";
 39:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 40:     vector<int>::iterator new_end = remove_if(v.begin(), v.end(),
 41:         isDivisibleByThree);
 42:     cout << "\nSize of vector immediately after "
 43:         "the call to remove_if:     " << v.size();
 44:     cout << "\nCapacity of vector immediately after "
 45:         "the call to remove_if: " << v.capacity();
 46:     cout << "\nContents of vector immediately after "
 47:         "the call to remove_if:\n";
 48:     for (vector<int>::size_type i=0; i<v.size(); i++)
 49:         cout << v.at(i) << " ";
 50:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');

 52:     cout << "\nNow we erase the last five values of the vector.";
 53:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 54:     v.erase(new_end, v.end());
 55:     cout << "\nSize of vector immediately after the call to erase:     "
 56:         << v.size();
 57:     cout << "\nCapacity of vector immediately after the call to erase: "
 58:         << v.capacity();
 59:     cout << "\nContents of vector immediately after the call to erase:\n";
 60:     for (vector<int>::size_type i=0; i<v.size(); i++)
 61:         cout << v.at(i) << " ";
 62:     cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
 63: }