Source of unique2a.cpp


  1: //unique2a.cpp

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

  8: /**
  9: Determines if two integers are both divisible by 3.
 10: Pre:\n m and n both contain an integer.
 11: Post:\n Returns true if m and n are both divisible by 3,
 12: and otherwise false.
 13: */
 14: bool bothDivisibleByThree
 15: (
 16:     int m, //in
 17:     int n  //in
 18: )
 19: {
 20:     return (m%3 == 0) && (n%3 == 0);
 21: }

 23: int main()
 24: {
 25:     cout << "\nThis program illustrates the use of the STL unique() "
 26:         "algorithm\n(extended version) to remove adjacent duplicate "
 27:         "copies of integer\nvalues divisible by 3 from a vector of "
 28:         "integers.";
 29:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 31:     int a1[] = {1, 2, 2, 3, 3, 6, 5, 2, 6, 9, 12, 2, 2, 2, 9, 10, 11, 12};
 32:     vector<int> v1(a1, a1+18);
 33:     cout << "\nHere are the values in the first vector:\n";
 34:     for (vector<int>::size_type i=0; i<v1.size(); i++)
 35:         cout << v1.at(i) << " ";;
 36:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 38:     cout << "\nNow we remove all adjacent duplicate copies of the "
 39:         "\nvalues 2 and 3 and redisplay the values to confirm:\n";
 40:     vector<int>::iterator new_end =
 41:         unique(v1.begin(), v1.end(), bothDivisibleByThree);
 42:     vector<int>::iterator p = v1.begin();
 43:     while (p != new_end) cout << *p++ << " ";
 44:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 46:     int a2[] = {1, 1, 2, 3, 3, 3, 4, 5, 5, 6, 6, 7, 8, 9, 9, 9, 9, 10};
 47:     vector<int> v2(a2, a2+18);
 48:     cout << "\nHere are the values in the second vector:\n";
 49:     for (vector<int>::size_type i=0; i<v2.size(); i++)
 50:         cout << v2.at(i) << " ";;
 51:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 53:     cout << "\nNow we remove all adjacent duplicate copies of any "
 54:         "\nof the values and redisplay the values to confirm:\n";
 55:     new_end = unique(v2.begin(), v2.end(), bothDivisibleByThree);
 56:     p = v2.begin();
 57:     while (p != new_end) cout << *p++ << " ";
 58:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 59: }