Source of unique_copy2a.cpp


  1: //unique_copy2a.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_copy() "
 26:         "algorithm\n(extended version) to remove adjacent duplicate copies "
 27:         "of integer values\ndivisible by 3 from a vector of integers, and "
 28:         "simultaneously copy the\nremaining values to another vector.";
 29:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

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

 38:     int a12[] = {21, 22, 23, 24, 25, 26, 27, 28, 29,
 39:                  30, 31, 32, 33, 34, 35, 36, 37, 38};
 40:     vector<int> v12(a12, a12+18);
 41:     cout << "\nHere are the values in the destination vector:\n";
 42:     for (vector<int>::size_type i=0; i<v12.size(); i++)
 43:         cout << v12.at(i) << " ";;
 44:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 46:     cout << "\nNow we remove all adjacent duplicate copies of any "
 47:         " values divisible by 3\nfrom the source vector and copy the "
 48:         "remaining values to the destination\nvector, starting at the "
 49:         "third value in that destination vector.";
 50:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 51:     vector<int>::iterator output_end = unique_copy(v11.begin(), v11.end(),
 52:         v12.begin()+2, bothDivisibleByThree);

 54:     cout << "\nHere are the (unchanged) source vector values:\n";
 55:     vector<int>::iterator p = v11.begin();
 56:     while (p != v11.end()) cout << *p++ << " ";
 57:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 59:     cout << "\nAnd here are the destination vector values:\n";
 60:     p = v12.begin();
 61:     while (p != v12.end()) cout << *p++ << " ";
 62:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 64:     cout << "\nThe iterator returned by the call to unique_copy() is "
 65:         "pointing to the value " << *output_end << ".";
 66:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 67: }