优先级队列 和 改变结构体 的排序规则

参考了  :https://blog.csdn.net/m0_37925202/article/details/81916600

https://www.cnblogs.com/cielosun/p/5654595.html

能站在巨人的肩膀上,也是一种本事!


------------------------------------------
a < b < c < d .....       从这里出去 --->
------------------------------------------

自己瞎猜的, 这个图解释了 : 虽然是用小于号 排序,但是大的先出来。

接下来 定义4中情况的 优先级队列

1,int  类型,降序

#include<cstdio>
#include<queue>
using namespace std;
priority_queue <int> q;
int main()
{
    q.push(10),q.push(8),q.push(12),q.push(14),q.push(6);
    while(!q.empty())
        printf("%d ",q.top()),q.pop();
}



输出: 
14 12 10 8 6


还有种没有必要的写法

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

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

int a[5]={10,12,14,6,8};
int main()
{
    for(int i=0;i<5;i++)
        p.push(a[i]),q.push(a[i]);

    printf("less<int>:")
    while(!p.empty())
        printf("%d ",p.top()),p.pop();  

}

输出:
less:14 12 10 8 6

2,int 升序

#include<cstdio>
#include<queue>
using namespace std;
priority_queue <int,vector<int>,greater<int> > q;
int a[5]={10,12,14,6,8};
int main()
{
    for(int i=0;i<5;i++)
       q.push(a[i]);

    pritntf("\ngreater<int>:")
    while(!q.empty())
        printf("%d ",q.top()),q.pop();
}

输出:
greater:6 8 10 12 14

3,按结构体中某元素降序

#include<cstdio>
#include<queue>
using namespace std;
struct node
{
    int x,y;
    bool operator < (const node & a) const
    {
        return x<a.x;
    }
}k;
priority_queue <node> q;
int main()
{
    k.x=10,k.y=100; q.push(k);
    k.x=12,k.y=60; q.push(k);
    k.x=14,k.y=40; q.push(k);
    k.x=6,k.y=80; q.push(k);
    k.x=8,k.y=20; q.push(k);
    while(!q.empty())
    {
        node m=q.top(); q.pop();
        printf("(%d,%d) ",m.x,m.y);
    }
}


输出: 
(14,40) (12,60) (10,100) (8,20) (6,80)


还是看那个图
------------------------------------------
a < b < c < d .....       从这里出去 --->
------------------------------------------

所以 是按照 a.x 从大到小出来的


4 按结构体中某元素升序

#include<cstdio>
#include<queue>
using namespace std;
struct node
{
    int x,y;
    bool operator < (const node & a) const
    {
        return x>a.x;
    }
}k;
priority_queue <node> q;
int main()
{
    k.x=10,k.y=100; q.push(k);
    k.x=12,k.y=60; q.push(k);
    k.x=14,k.y=40; q.push(k);
    k.x=6,k.y=80; q.push(k);
    k.x=8,k.y=20; q.push(k);
    while(!q.empty())
    {
        node m=q.top(); q.pop();
        printf("(%d,%d) ",m.x,m.y);
    }
}


明白了第三个,这个就很好理解了

以我对自己的了解,先掌握这四种就行了,,

别整些花里胡哨的

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值