1、重载定位符号
定义友元函数,重载某定义的数据结构的 “<”操作符号,以下是优先队列中的最大堆的定义(默认为最小堆),elemetype数据结构中的num元素小的优先输出(最小堆)。
//重载小于符号,num最小的优先输出
friend bool operator < (const elemtype &e1,const elemtype &e2){
return e1.num>e2.num ;
}
//结构体中重载 符号:
struct node{
int id;
int x;
int y;
node(int iid,int xx,int yy):id(iid),x(xx),y(yy){}
bool operator < (const node &no){
return pow(this->x,2)+pow(this->y,2) < pow(no.x,2)+pow(no.y,2);
}
};
//类中重载
class Node{
public:
Node(int iid,int xx,int yy):id(iid),x(xx),y(yy){}
bool operator < (const node &no){
return pow(this->x,2)+pow(this->y,2) < pow(no.x,2)+pow(no.y,2);
}
private:
int id;
int x;
int y;
};
2、优先队列的使用
priority_queue<elemtype> pqu; //由此我们再重载elemtype数据类型的<符号,得到我们所想要的最小堆和最大堆
注意:与队列不同的是获取顶部元素,优先队列中使用的是top()方法,而队列中使用的front方法。优先队列实际上是一个最小堆。
3、实际应用:迪杰斯特拉求最短路径,获取到每次的最佳边。