优先级队列是一种用来维护一组元素构成的组合的数据结构,其中每个元素都有一个关键字key,元素之间的比较都是通过key来比较的。优先队列包括最大优先队列和最小优先队列,优先队列的应用比较广泛,比如作业系统中的调度程序,当一个作业完成后,需要在所有等待调度的作业中选择一个优先级最高的作业来执行,并且也可以添加一个新的作业到作业的优先队列中。其示例使用如下,注意要引入相应的头文件queue。
int main(){
//优先级队列
priority_queue<int> p1; //默认情况下是最大值优先队列
priority_queue<int,vector<int>,less<int>> p2; //自定义的最大值优先级队列
priority_queue<int,vector<int>,greater<int>> p3; //自定义的最小值优先级队列
//测试数据
int tmp;
for (int i = 0; i < 10; ++i) {
tmp=rand()/1000000+1;
p1.push(tmp);
p2.push(tmp);
p3.push(tmp);
}
//输出效果
while(!p1.empty()){
cout<<p1.top()<<" ";
p1.pop();
}
cout<<endl;
while(!p2.empty()){
cout<<p2.top()<<" ";
p2.pop();
}
cout<<endl;
while(!p3.empty()){
cout<<p3.top()<<" ";
p3.pop();
}
cout<<endl;
return 0;
}
对此当优先级队列内部的元素复杂的时候,可以作如下案例
//重载优先级队列符号
class Person{
public:
Person(int age,string name){
this->name=name;
this->age=age;
}
int getAge(){
return this->age;
}
string getName(){
return this->name;
}
bool operator < (const Person &p)const{
return age<p.age;
}
private:
int age;
string name;
};
int main(){
priority_queue<Person> ps;
Person p1(11,"张三");
Person p2(14,"李四");
Person p3(12,"王无");
ps.push(p1);
ps.push(p2);
ps.push(p3);
while(!ps.empty()){
Person p=ps.top();
cout<<p.getName()<<"->"<<p.getAge()<<" ";
ps.pop();
}
cout<<endl;
return 0;
}
此时要注意的是在重载最大值优先级队列的时候,只能重载小于号(<),如果重载大于号,则编译时会报如下错误:
error: no match for 'operator<' (operand types are 'const Person' and 'const Person')
点开错误代码会发现以下代码
template<typename _Tp>
struct greater : public binary_function<_Tp, _Tp, bool>
{
_GLIBCXX14_CONSTEXPR
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x > __y; }
};
/// One of the @link comparison_functors comparison functors@endlink.
template<typename _Tp>
struct less : public binary_function<_Tp, _Tp, bool>
{
_GLIBCXX14_CONSTEXPR
bool
operator()(const _Tp& __x, const _Tp& __y) const
{ return __x < __y; }
};
即会发现在less的结构体中并没有定义">"的运算符所以找不到匹配的运算符从而出错。此时也可以类比以上的最小值优先队列可以发现在其中也不能重载最"<"的运算符。