优先队列与结构体

priority_queue <int> q:默认将队列中的数从大到小排序;

priority_queue <int,vector<int>,greater<int> > q:从小到大排序;

priority_queue <int,vector<int>,less<int> > q:从大到小排序;

队列中可以的元素可以是结构体,一个结构体中肯定有不同参数,优先队列肯定要有一个排序的参数,所以就需要友元来定义结构体的元素的优先度;

  • priority_queue <tree> q:
struct tree
{
    int dj;
    int id;
    friend bool operator <(const tree x,const tree y)
    {
        if(x.dj==y.dj)
        {
            return x.id>y.id;
        }
        else
        {
            return x.dj<y.dj;
        }
    }
};

当第一个参数dj的有限度相同时,在优先队列中,id小的在队列前方;

当第一个参数dj不同时,在优先队列中,dj大的在队列前方;

  • priority_queue <node> q:
struct node
{
    string name;
    int sz;
    int yxj;
    int id;
    friend bool operator <(node a,node b)
    {
       if(a.yxj==b.yxj)
       {
             return a.id>b.id;
       }
       else
       {
             return a.yxj>b.yxj;
       }
    }
};

当结构体中的yxj相同时,结构体中的id小的在优先队列前方;

当结构体中的yxj不同时,结构体中的yxj小的在优先队列的前方

  • priority_queue <node,vector<node>,cmp> q:
struct node
{
    string name;
    int sz;
    int yxj;
    int id;
};
struct cmp
{
    bool operator( )(const node a,const node b) const
    {
        if(a.yxj==b.yxj)
       {
             return a.id>b.id;
       }
       else
       {
             return a.yxj>b.yxj;
       }
    }
}; 

构造自定义函数cmp

当结构体中的yxj相同时,结构体中的id小的在优先队列前方;

当结构体中的yxj不同时,结构体中的yxj小的在优先队列的前方。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容