【STL之priority_queue】priority_queue针对不同数据类型的使用方法

priority_queue针对不同数据类型的使用方法

参考网站:https://blog.csdn.net/qq_19656301/article/details/82490601
https://blog.csdn.net/c20182030/article/details/70757660?locationNum=5&fps=1

非结构体优先队列

#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#include <functional>
using namespace std;
priority_queue<int, vector<int>, greater<int> > q; //小顶堆
//priority_queue<int, vector<int>, less<int> > q;  //大顶堆
//元素为int类型的优先队列 优先规则由greater以及less决定
int main(){
    int n, x;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++){
        scanf("%d", &x);
        q.push(x);
    }
    while (!q.empty()){ //队列顶端始终为符合优先规则的优先元素
        printf("%d ", q.top());
        q.pop();
    }
    return 0;
}

pair类型优先队列

#include <iostream>
#include <queue>
#include <cstdio>
#include <vector>
#include <utility>
#include <functional>
using namespace std;
typedef pair<int, int> info;
priority_queue<info, vector<info>, greater<info> > q; //小顶堆
//priority_queue<info, vector<info>, less<info> > q;  //大顶堆
//元素为info类型的优先队列 优先规则由greater以及less决定
//pair的排序规则为首先比较第一个数值大小 如第一数值相等再比较第二个数值大小
int main(){
    int n, x, y;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++){
        scanf("%d %d", &x, &y);
        q.push(make_pair(x, y));
    }
    while (!q.empty()){ //队列顶端始终为符合优先规则的优先元素
        printf("%d %d\n", q.top().first, q.top().second);
        q.pop();
    }
    return 0;
}

结构体优先队列

#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
struct node{
    int x, y;
    //重载 < 运算符 自定义结构体比较规则
    bool operator < (const node &b) const{
        return this->x > b.x; 	//小顶堆
        //return this->x < b.x; //大顶堆
    }
    node(const int &x, const int &y){ //结构体初始化
        this->x = x;
        this->y = y;
    }
};
priority_queue<node> q;
//元素为node类型的优先队列 优先规则由结构体重载运算符决定
int main(){
    int n, x, y;
    scanf("%d", &n);
    for (int i = 1; i <= n; i++){
        scanf("%d%d", &x, &y);
        q.push(node(x, y));
    }
    while (!q.empty()){ //队列顶端始终为符合优先规则的优先元素
        printf("%d %d\n", q.top().x, q.top().y);
        q.pop();
    }
    node tmp1(3, 5);
    node tmp2(4, 2);
    //旨在说明 要注意这里的 < 不是小于号 而是一种比较规则
    //默认采取小顶堆 则这里的 < 起到的作用是大于号
    if (tmp1 < tmp2) printf("tmp1 > tmp2\n");
    else printf("tmp1 < tmp2\n");
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值