[cpp]
/*
This is a free Program, You can modify or redistribute it under the terms of GNU
*Description:優先級隊列使用范例
*Language: C++
*Development Environment: VC6.0
*Author: Wangzhicheng
*E-mail: [email protected]
*Date: 2012/10/18
*/
/*
priority_queue 優先級隊列是一個擁有權值概念的單向隊列queue,
在這個隊列中,所有元素是按優先級排列的。
在STL的具體實現中,priority_queue也是以別的容器作為底部結構,再根據堆的處理規則來調整元素之間的位置
*/
#include <iostream>
#include <queue>
#include <string>
using namespace std;
const int max=1000;
class Person {
private:
int nice; //優先級
string name;
public:
Person(int nice=0,string name="") {
this->nice=nice;
this->name=name;
}
Person(const Person& p) {
nice=p.nice;
name=p.name;
}
Person& operator=(const Person& p) {
nice=p.nice;
name=p.name;
return *this;
}
friend bool operator<(const Person &p1,const Person &p2) {
if(p1.getNice()!=p2.getNice()) {
return p1.getNice() < p2.getNice();
}
return p1.getName() < p2.getName();
}
void setNice(int nice) {
this->nice=nice;
}
int getNice() const {
return nice;
}
void setName(string name) {
this->name=name;
}
string getName() const {
return name;
}
friend istream& operator >>(istream& is,Person &p) {
int nice;
string name;
cout<<"請輸入人員的優先級:";
cin>>nice;
if(!cin.good()) {
cerr<<"輸入錯誤!"<<endl;
is.clear();
return is;
}
if(nice<0 || nice>=max) {
cerr<<"輸入范圍錯誤!"<<endl;
is.clear();
return is;
}
cout<<"請輸入人員的姓名:";
cin>>name;
p.setNice(nice);
p.setName(name);
return is;
}
friend ostream& operator <<(ostream &os,Person &p) {
os<<"姓名:"<<p.getName()<<endl;
os<<"優先級:"<<p.getNice()<<endl;
return os;
}
};
class LessThan {
public:
bool operator()(const Person &p1,const Person &p2) {
if(p1.getNice()!=p2.getNice()) {
return p1.getNice() < p2.getNice();
}
return p1.getName() < p2.getName();
}
};
const int N=4;
void main() {
int nice;
string name;
int i;
Person p;
priority_queue<Person,vector<Person> >q;
for(i=0;i<N;i++) {
cout<<"請輸入第"<<i<<"個人員信息"<<endl;
cin>>p;
q.push(p);
}
while(q.empty()==false) {
cout<<q.top();
q.pop();
}
}