C++ priority_queue 常见用法全解(代码版)

priority_queue的用法和queue基本一样,难点在于自定义类型的自动排序。一共有三种写法。默认是vector作为底层结构。

代码实例1:

class struc{
public:
    int x;
    int y;
    struc(int a, int b): x(a), y(b){}
    
    bool operator<(const struc& b) const        //自定义排序。写在类里面必须是const函数!
    {
        return this->x * this->y > b.x * b.y;
    }
};

void priority_queue_test()
{
    priority_queue<int> pq1;    //默认大顶堆,大的在前面。
    priority_queue<int, vector<int>, greater<int> > pq2;  //小顶堆,小的在前面
    
    
    priority_queue<struc> Mypq;
    
    Mypq.push(struc(2, 2));
    Mypq.push(struc(1, 5));
    
    while(!Mypq.empty())
    {
        cout<<Mypq.top().x<<" "<<Mypq.top().y<<endl;           //注意priority_queue取头元素是 top();
        Mypq.pop();
    }
}

代码实例2:


class struc{
public:
    int x;
    int y;
    struc(int a, int b): x(a), y(b){}
};

struct compare{
    bool operator()(const struc& a, const struc& b)     //自定义排序。
    {
        return a.x * b.y < b.x * b.y;
    }
};

void priority_queue_test()
{
    priority_queue<struc, vector<struc>, compare> Mypq;	//这种情况就必须写一个struct compare
    
    Mypq.push(struc(2, 2));
    Mypq.push(struc(1, 5));
    while(!Mypq.empty())
    {
        cout<<Mypq.top().x<<" "<<Mypq.top().y<<endl;           //注意priority_queue取头元素是 top();
        Mypq.pop();
    }
}



  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值