1 #include <iostream>
2 #include <assert.h>
3 #include <set>
4 #include <string>
5 using namespace std;
6
7 struct employee
8 {
9 //Member Function
10 public:
11 employee() {} //默认构造函数
12 employee(long eID, string e_Name, float e_Salary);
13
14 //Attribute
15 public:
16 long ID; //Employee ID
17 string name; //Employee Name
18 float salary; //Employee Salary
19 };
20
21 //员工类构造函数
22 employee::employee(long eID, string e_Name, float e_Salary)
23 : ID(eID), name(e_Name), salary(e_Salary) {}
24
25 //用于对Set容器排序的函数对象
26 class KeyComp
27 {
28 public:
29 bool operator() (const employee& A, const employee& B)
30 {
31 return (A.salary < B.salary);
32 }
33 };
34
35
36 //定义一个元素类型为employee、按KeyComp排序的Set容器类型
37 typedef set<employee, KeyComp> EMPLOYEE_SET;
38 //定义MultiSet容器的随机访问迭代器类型
39 typedef set<employee, KeyComp>::iterator EMPLOYEE_IT;
40 //定义MultiSet容器的反向迭代器类型
41 typedef set<employee, KeyComp>::reverse_iterator EMPLOYEE_RIT;
42
43 //函数功能:正向输出Set容器对象的所有元素
44 //参数:一个Set容器对象
45 //返回值:无
46 void output_set(EMPLOYEE_SET e)
47 {
48 assert(!e.empty());
49 EMPLOYEE_IT it;
50 for (it = e.begin(); it != e.end(); it++)
51 {
52 cout << (*it).ID << '\t' << (*it).name << '\t' << (*it).salary << endl;
53 }
54 }
55
56 //函数功能:逆向输出Set容器对象的所有元素
57 //参数:一个Set容器对象
58 //返回值:无
59 void reverse_output_set(EMPLOYEE_SET e)
60 {
61 assert(!e.empty());
62 EMPLOYEE_RIT rit;
63 for (rit = e.rbegin(); rit != e.rend(); rit++)
64 {
65 cout << (*rit).ID << '\t' << (*rit).name << '\t' << (*rit).salary << endl;
66 }
67 }
68
69 int main(int argc, char* argv[])
70 {
71 EMPLOYEE_SET employees; //声明一个容器对象
72
73 //下面的三条语句分别构造三个employee对象,然后插入MultiSet容器对象employees
74 employees.insert(EMPLOYEE_SET::value_type(100, "huahua", 20000));
75 employees.insert(EMPLOYEE_SET::value_type(101, "jiafeng", 8000));
76 employees.insert(EMPLOYEE_SET::value_type(102, "guangli", 10000));
77
78 //注意下面的两条语句,因为是Set,不允许有重复的值,所以两个employee对象只会有一条加入到Set容器
79 employees.insert(EMPLOYEE_SET::value_type(103, "jiahui", 12000));
80 employees.insert(EMPLOYEE_SET::value_type(103, "jiahui", 12000));
81
82 //正向和逆向输出Set容器对象的所有元素
83 assert(!employees.empty());
84 cout << "From Head To Tail:" << endl;
85 output_set(employees);
86
87 cout << "From Tail To Head:" << endl;
88 reverse_output_set(employees);
89
90
91 cout << "Set容器对象employees是否为空? " << (employees.empty() ? "TRUE" : "FALSE") << endl;
92 cout << "Set容器对象employees共有" << employees.size() << "个employee对象!" << endl;
93
94 return 0;
95 }
posted on 2009-02-09 16:48
混沌的云 阅读(672)
评论(0) 编辑 收藏 引用