Source of stable_sort1a.cpp


  1: //stable_sort1a.cpp

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

  8: struct Point
  9: {
 10:     int x;
 11:     int y;
 12:     //bool operator<(Point p) { return this->x < p.x; }
 13: };
 14: bool operator<(Point p1, Point p2) {return p1.x < p2.x;}
 15: ostream& operator<<
 16: (
 17:     ostream& os,
 18:     const Point& p
 19: )
 20: {
 21:     os << "(" << p.x << "," << p.y << ")";
 22:     return os;
 23: }

 25: int main()
 26: {
 27:     cout << "\nThis program illustrates the use of the STL stable_sort() "
 28:         "algorithm (default\nversion) to sort Points, where one Point "
 29:         "comes before another if and only if\nits x-coordinate is less "
 30:         "than the x-coordinate of the second Point."
 31:         
 32:         "\n\nAn interesting exercise is to change the call to "
 33:         "stable_sort() to a call to\nsort() and observe "
 34:         "the difference in output, if any.";
 35:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 37:     Point a[] ={{2,4}, {2,3}, {5,5}, {3,7}, {3,5}, {1,2}, {1,1}};
 38:     vector<Point> v(a, a+7);
 39:     cout << "\nHere are the contents of the vector:\n";
 40:     for (vector<int>::size_type i=0; i<v.size(); i++)
 41:         cout << v.at(i) << " ";
 42:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 44:     stable_sort(v.begin(), v.end());

 46:     cout << "\nAnd here are the contents of the sorted vector:\n";
 47:     for (vector<Point>::size_type i=0; i<v.size(); i++)
 48:         cout << v.at(i) << " ";
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 50: }