Source of partition1a.cpp


  1: //partition1a.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 partition() "
 24:         "algorithm to\npartition the integer values in a vector of "
 25:         "integers into two groups:\nthose that are divisible by 3, and "
 26:         "those that are not.";
 27:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 29:     int a[] ={11, 7, 9, 4, 8, 12, 2, 5, 3, 10, 1, 6};
 30:     vector<int> v(a, a+12);
 31:     cout << "\nHere are the contents of the vector:\n";
 32:     for (vector<int>::size_type i=0; i<v.size(); i++)
 33:         cout << v.at(i) << " ";
 34:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 36:     vector<int>::iterator p = partition(v.begin(), v.end(),
 37:         isDivisibleByThree);
 38:     cout << "\nAnd here are the contents of the partitioned vector:\n";
 39:     for (vector<int>::size_type i=0; i<v.size(); i++)
 40:         cout << v.at(i) << " ";
 41:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 43:     cout << "\nThe iterator p returned by the algorithm points to ";
 44:     if (p == v.end())
 45:         cout << "\nthe end of the ouput container.";
 46:     else
 47:         cout << "the value " << *p << ".";
 48:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 49: }