multiset 应用示例

/*
 * Copyright (c) 2006 All rights reserved.
 * 文件名:MultiSet.cpp
 *
 * 文件标识:MultiSet
 * 摘要:MultiSet容器编程示例
 * 输入:无
 * 输出:输出MultiSet容器对象的信息
 *
 * 当前版本 0.01
 * 作者:罗
 * 完成日期:2006年4月5日
 */

#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) {}

//用于对MultiSet容器排序的函数对象
class KeyComp
{
public:
	bool operator() (const employee& A, const employee& B)
	{
		return (A.salary < B.salary);
	}
};


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

//函数功能:正向输出MultiSet容器对象的所有元素
//参数:一个MultiSet容器对象
//返回值:无
void output_multiset(EMPLOYEE_MULTISET 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;
	}
}

//函数功能:逆向输出MultiSet容器对象的所有元素
//参数:一个MultiSet容器对象
//返回值:无
void reverse_output_multiset(EMPLOYEE_MULTISET 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_MULTISET employees;           //声明一个容器对象
	
	//下面的三条语句分别构造三个employee对象,然后插入MultiSet容器对象employees
	employees.insert(EMPLOYEE_MULTISET::value_type(100, "huahua", 20000));
	employees.insert(EMPLOYEE_MULTISET::value_type(101, "jiafeng", 8000));
	employees.insert(EMPLOYEE_MULTISET::value_type(102, "guangli", 10000));

	//注意下面的两条语句,因为是MultiSet,允许有重复的值,所以两个employee对象都会加入到MultiSet容器
	employees.insert(EMPLOYEE_MULTISET::value_type(103, "jiahui", 12000));
	employees.insert(EMPLOYEE_MULTISET::value_type(103, "jiahui", 12000));

	//正向和逆向输出MultiSet容器对象的所有元素
	assert(!employees.empty());
	cout << "From Head To Tail:" << endl;
	output_multiset(employees);

	cout << "From Tail To Head:" << endl;
	reverse_output_multiset(employees);


	cout << "MultiSet容器对象employees是否为空? " << (employees.empty() ? "TRUE" : "FALSE") << endl;
	cout << "MultiSet容器对象employees共有" << employees.size() << "个employee对象!" << endl;

	return 0;
}

你可能感兴趣的:(multiset 应用示例)