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

#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都不关用了,不过重载符号不同,

猜你喜欢

转载自blog.csdn.net/qq_41325698/article/details/82048083