STL学习之list
1 // Standard Template Library example using a class.
2
3 #include "stdafx.h"
4 #include <iostream>
5 #include <list>
6 using namespace std;
7
8 // The List STL template requires overloading operators =, == and <.
9
10 class AAA
11 {
12 friend ostream &operator<<(ostream &, const AAA &);
13
14 public:
15 int x;
16 int y;
17 float z;
18
19 AAA();
20 AAA(const AAA &);
21 ~AAA(){};
22 AAA &operator=(const AAA &rhs);
23 int operator==(const AAA &rhs) const;
24 int operator<(const AAA &rhs) const;
25 };
26
27 AAA::AAA() // Constructor
28 {
29 x = 0;
30 y = 0;
31 z = 0;
32 }
33
34 AAA::AAA(const AAA ©in) // Copy constructor to handle pass by value.
35 {
36 x = copyin.x;
37 y = copyin.y;
38 z = copyin.z;
39 }
40
41 ostream &operator<<(ostream &output, const AAA &aaa)
42 {
43 output << aaa.x << ' ' << aaa.y << ' ' << aaa.z << endl;
44 return output;
45 }
46
47 AAA& AAA::operator=(const AAA &rhs)
48 {
49 this->x = rhs.x;
50 this->y = rhs.y;
51 this->z = rhs.z;
52 return *this;
53 }
54
55 int AAA::operator==(const AAA &rhs) const
56 {
57 if( this->x != rhs.x) return 0;
58 if( this->y != rhs.y) return 0;
59 if( this->z != rhs.z) return 0;
60 return 1;
61 }
62
63 // This function is required for built-in STL list functions like sort
64 int AAA::operator<(const AAA &rhs) const
65 {
66 if( this->x == rhs.x && this->y == rhs.y && this->z < rhs.z) return 1;
67 if( this->x == rhs.x && this->y < rhs.y) return 1;
68 if( this->x < rhs.x ) return 1;
69 return 0;
70 }
71
72 int main()
73 {
74 list<AAA> L;
75 AAA Ablob ;
76
77 Ablob.x=7;
78 Ablob.y=2;
79 Ablob.z=4.2355;
80 L.push_back(Ablob); // Insert a new element at the end
81
82 Ablob.x=5;
83 L.push_back(Ablob); // Object passed by value. Uses default member-wise
84 // copy constructor
85 Ablob.z=3.2355;
86 L.push_back(Ablob);
87
88 Ablob.x=3;
89 Ablob.y=7;
90 Ablob.z=7.2355;
91 L.push_back(Ablob);
92
93 list<AAA>::iterator i;
94
95 for(i=L.begin(); i != L.end(); ++i) cout << (*i).x << " "; // print member
96 cout << endl;
97
98 for(i=L.begin(); i != L.end(); ++i) cout << *i << " "; // print with overloaded operator
99 cout << endl;
100
101 cout << "Sorted: " << endl;
102 L.sort();
103 for(i=L.begin(); i != L.end(); ++i) cout << *i << " "; // print with overloaded operator
104 cout << endl;
105
106 return 0;
107 }
References:
[1], C++ STL Tutorial. http://www.yolinux.com/TUTORIALS/LinuxTutorialC++STL.html
posted on 2011-05-15 17:17 Joshua Leung 阅读(188) 评论(0) 收藏 举报