c++优先队列使用方法

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、实际应用:迪杰斯特拉求最短路径,获取到每次的最佳边。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值