队列 之优先队列(priority_queue)

priority_queue的模板参考定义 :

template<class T,class Cont =vector<T>,class Pred=less<Cont::value_type>>

class priority_queue

{

//中间省略

}

 

int a[]={1,2,3,4,5,6,7,8,9,10};

priority_queue<int>pr(a,a+9);     //通过构造函数将a[0]~a[8]送入优先队列

pr.push(a[9]);                           //通过函数将a[9]送入优先队列

 

while(!pr.empty())

{                                          //入队顺序为 1,2,3,4,5,6,7,8,9,10

cout<<pr.top()<<"\t";            //出队顺序为 10,9,8,7,6,5,4,3,2,1

pr.pop();

}

归纳知识点 :

(1) 易知,出队是谁优先级高,谁先出队。由于输入队列是升序排列,与输出队列刚好相反,若需要按原序列输出,仍然用priority_queue

  只需把priority_queue<int>pr(a,a+9) 改为 priority_queue<int,vector<int>,greater<int>>pr(a,a+9) 即可

因为priority_queue<int>pr(a,a+9) 相当于priority_queue<int,vector,less<int>>pr(a,a+9) 

 

对于8中基本类型  若想按升序排列,则可以直接按上述的方式声明 ; 如果是自己写的结构体或者类,若想实现按升序排列,则需要在结构体或者类中将其实现。

下面的代码是在类中重载操作符<的代码:(按NO升序排列;如果NO相等,则按lenth升序排列;如果lenth也相等,则按width升序排列)

bool operator<(const squar& s)const
{
int NO1=s.GetNO();
int lenth1=s.GetLenth();
int width1=s.GetWidth();
if(NO>NO1) return true;
if((NO==NO1)&&(lenth>lenth1)) return true;
if((NO==NO1)&&(lenth==lenth1)&&(width>width1)) return true;
return false;
}

 

posted @ 2014-03-28 10:12  zhoudan  阅读(217)  评论(0编辑  收藏  举报