分类:
2012-05-27 03:12:54
/*
* Copyright (c) 2006 All rights reserved.
* 文件名:Set.cpp
*
* 文件标识:Set
* 摘要:Set容器编程示例
* 输入:无
* 输出:输出Set容器对象的信息
*
* 当前版本 0.02
* 作者:罗
* 完成日期:2006年4月5日
*/
#include
#include
#include
#include
using namespace std;
struct employee
{
//Member Function
public:
employee() {} //默认构造函数
employee(long eID, string e_Name, float e_Salary);
//Attribute
public:
long ID; //Employee ID
string name; //Employee Name
float salary; //Employee Salary
};
//员工类构造函数
employee::employee(long eID, string e_Name, float e_Salary)
: ID(eID), name(e_Name), salary(e_Salary) {}
//用于对Set容器排序的函数对象
class KeyComp
{
public:
bool operator() (const employee& A, const employee& B)
{
return (A.salary < B.salary);
}
};
//定义一个元素类型为employee、按KeyComp排序的Set容器类型
typedef set
//定义MultiSet容器的随机访问迭代器类型
typedef set
//定义MultiSet容器的反向迭代器类型
typedef set
//函数功能:正向输出Set容器对象的所有元素
//参数:一个Set容器对象
//返回值:无
void output_set(EMPLOYEE_SET e)
{
assert(!e.empty());
EMPLOYEE_IT it;
for (it = e.begin(); it != e.end(); it++)
{
cout << (*it).ID << '\t' << (*it).name << '\t' << (*it).salary << endl;
}
}
//函数功能:逆向输出Set容器对象的所有元素
//参数:一个Set容器对象
//返回值:无
void reverse_output_set(EMPLOYEE_SET e)
{
assert(!e.empty());
EMPLOYEE_RIT rit;
for (rit = e.rbegin(); rit != e.rend(); rit++)
{
cout << (*rit).ID << '\t' << (*rit).name << '\t' << (*rit).salary << endl;
}
}
int main(int argc, char* argv[])
{
EMPLOYEE_SET employees; //声明一个容器对象
//下面的三条语句分别构造三个employee对象,然后插入MultiSet容器对象employees
employees.insert(EMPLOYEE_SET::value_type(100, "huahua", 20000));
employees.insert(EMPLOYEE_SET::value_type(101, "jiafeng", 8000));
employees.insert(EMPLOYEE_SET::value_type(102, "guangli", 10000));
//注意下面的两条语句,因为是Set,不允许有重复的值,所以两个employee对象只会有一条加入到Set容器
employees.insert(EMPLOYEE_SET::value_type(103, "jiahui", 12000));
employees.insert(EMPLOYEE_SET::value_type(103, "jiahui", 12000));
//正向和逆向输出Set容器对象的所有元素
assert(!employees.empty());
cout << "From Head To Tail:" << endl;
output_set(employees);
cout << "From Tail To Head:" << endl;
reverse_output_set(employees);
cout << "Set容器对象employees是否为空? " << (employees.empty() ? "TRUE" : "FALSE") << endl;
cout << "Set容器对象employees共有" << employees.size() << "个employee对象!" << endl;
return 0;
}
|