1: //stable_partition1a.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: ostream& operator<<
15: (
16: ostream& os,
17: const Point& p
18: )
19: {
20: os << "(" << p.x << "," << p.y << ")";
21: return os;
22: }
24: /**
25: Determines if the x-coordinate of a point is divisible by 3.
26: @pre p contains a Point.
27: @post Returns true if the x-coordinate of p is divisible by 3,
28: and otherwise false.
29: */
30: bool isDivisibleByThree
31: (
32: Point p //in
33: )
34: {
35: return (p.x % 3 == 0);
36: }
38: int main()
39: {
40: cout << "\nThis program illustrates the use of the STL "
41: "stable_partition() algorithm to\npartition the Point "
42: "values in a vector of Points into two groups: those "
43: "whose\nx-coordinate is divisible by 3, and those for "
44: "whom this is not true."
45:
46: "\n\nAn interesting exercise is to change the call to "
47: "stable_partition() to a call\nto partition() and observe "
48: "the difference in output.";
49: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
51: Point a[] ={ {1,2}, {3,4}, {4,5}, {6,7} };
52: vector<Point> v(a, a+4);
53: cout << "\nHere are the contents of the vector:\n";
54: for (vector<int>::size_type i=0; i<v.size(); i++)
55: cout << v.at(i) << " ";
56: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
58: vector<Point>::iterator p = stable_partition(v.begin(), v.end(),
59: isDivisibleByThree);
60: cout << "\nAnd here are the contents of the partitioned vector:\n";
61: for (vector<Point>::size_type i=0; i<v.size(); i++)
62: cout << v.at(i) << " ";
63: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
65: cout << "\nThe iterator p returned by the algorithm points to ";
66: if (p == v.end())
67: cout << "\nthe end of the ouput container.";
68: else
69: cout << "the value " << *p << ".";
70: cout << "\nPress Enter to continue ... "; cin.ignore(80, '\n');
71: }