C++优先级队列+重载

6 篇文章 0 订阅
2 篇文章 0 订阅

1、int类型

C++的优先级队列默认是大顶堆,大数的优先级高,即将多个数放入优先级队列后,队首(下一个出队)元素是这些数里面最大的那个。

默认情况等价于:

priority_queue<int,vector<int>,less<int> >q;

代码:

#include <iostream>
#include <queue>
using namespace std;

void run1(){
    priority_queue<int> q;
    q.push(2),q.push(5),q.push(1),q.push(7),q.push(3);
    while(!q.empty()){
        cout<<q.top()<<" ";
        q.pop();
    }
    cout<<endl;
}
int main(){
    run1();
}

输出结果:

7 5 3 2 1

如果想要小数位于队首,需要改变优先级:

priority_queue<int,vector<int>,greater<int> >q;

这样的输出是:

1 2 3 5 7

2、结构体

例如一个结构体中有连个元素x和y,我们想要让x值大的优先级更高,即位于队首。

需要对结构体重载运算符,代码:

#include <iostream>
#include <queue>
using namespace std;
struct node{
    int x, y;
    node(int _x, int _y): x(_x), y(_y){}
    bool operator < (const node &a)const{
        return x < a.x;
    }
};

void run2(){
    priority_queue<node> q;
    q.push(node(2,4)),q.push(node(5,2)),q.push(node(1,1)),q.push(node(7,0)),q.push(node(3,10));
    while(!q.empty()){
        node tmp = q.top();
        q.pop();
        cout<<tmp.x<<" "<<tmp.y<<endl;
    }
}
int main(){
    run2();
}

输出结果:

7 0
5 2
3 10
2 4
1 1

如果让小的x优先级更高,则这样重载:

struct node{
    int x, y;
    node(int _x, int _y): x(_x), y(_y){}
    bool operator < (const node &a)const{
        return x > a.x;
    }
};

输出结果:

1 1
2 4
3 10
5 2
7 0

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值