优先对列 对结构体进行排序,

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
struct node
{
    int d,w;
    
};
bool operator < (const node & x,const node & y)
{
    if(y.w==x.w)
    return x.d>y.d;                   
    else
    return x.w>y.w;
}
int main()
{
    priority_queue<node> q;
    int n,i,j,t;
    node s;
    freopen("1.txt","r",stdin);
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>s.d>>s.w;
        q.push(s);
    }
    while(!q.empty())
    {
        node r=q.top();
        printf("%d  %d\n",r.d,r.w);
        q.pop();
    }
    return 0;
}

把重载函数放在外面,结果为下图,

 

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
struct node
{
    int d,w;
    bool operator < (const node & x)const
    {
        if(w==x.w)
            return x.d>d;
        else
            return x.w>w;
    }
};

int main()
{
    priority_queue<node,vector<node>,less<node> > q;
    int n,i,j,t;
    node s;
    freopen("1.txt","r",stdin);
    cin>>n;
    for(i=0; i<n; i++)
    {
        cin>>s.d>>s.w;
        q.push(s);
    }
    while(!q.empty())
    {
        node r=q.top();
        printf("%d  %d\n",r.d,r.w);
        q.pop();
    }
    return 0;
}

把重载函数放结构体里面,结果如下:

#include<iostream>
#include<cstdio>
#include<queue>
#include<algorithm>
#include<vector>
using namespace std;
struct node
{
    int d,w;
    bool operator < (const node & x)const
    {
        if(w==x.w)
            return x.d>d;
        else
            return x.w>w;
    }
};

int main()
{
    priority_queue<node > q;
    int n,i,j,t;
    node s;
    freopen("1.txt","r",stdin);
    cin>>n;
    for(i=0; i<n; i++)
    {
        cin>>s.d>>s.w;
        q.push(s);
    }
    while(!q.empty())
    {
        node r=q.top();
        printf("%d  %d\n",r.d,r.w);
        q.pop();
    }
    return 0;
}

对于这种情况,优先队列对结构体排序,如果重载函数在结构体里面,

struct node
{
    int d,w;
    bool operator < (const node & x)const
    {
        if(w==x.w)
            return x.d>d;
        else
            return x.w>w;
    }
};

这种形式,就是按return x.w>w;决定的,

struct node
{
    int d,w;
    
};
bool operator < (const node & x,const node & y)
{
    if(y.w==x.w)
    return x.d>y.d;                   
    else
    return x.w>y.w;
}

如果为这种形式,可以这样理解,x.w比y.w大,那么x就放在y后面,同理,x的d。。。。这点和STL的map和set对结构体排序不太一样,正好相反,https://blog.csdn.net/qq_41325698/article/details/81590968

还有一个小发现:只要,我定义了重载函数,不管是less还是greater都不关用了,不过重载符号不同,

 

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值