set的应用实例

#include <iostream>
#include <assert.h>
#include <set>
#include <string>
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
{
[color=red]public:
bool operator() (const employee& A, const employee& B)
{
return (A.salary < B.salary);
}[/color]};


//定义一个元素类型为employee、按KeyComp排序的Set容器类型
typedef set<employee, KeyComp> EMPLOYEE_SET;
//定义MultiSet容器的随机访问迭代器类型
typedef set<employee, KeyComp>::iterator EMPLOYEE_IT;
//定义MultiSet容器的反向迭代器类型
typedef set<employee, KeyComp>::reverse_iterator EMPLOYEE_RIT;

//函数功能:正向输出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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值