priority_queue,set,map自定义排序

在使用很多的priority_queue时候默认优先级并不适合题目要求,得自己定义优先级……

#include<bits/stdc++.h>
using namespace std;
struct node
{
    int x,y;
    friend bool operator<(node a,node b)
    {
        if(a.x!=b.x)
            return a.x<b.x;//x大的优先级高
        else return a.y<b.y;//y大的优先级高
    }
};
priority_queue<node>q4;
int main()
{
    int n;
    node a;
    while(scanf("%d",&n)==1)
    {
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&a.y,&a.x);
            q4.push(a);
        }
        while(!q4.empty())
        {
            printf("%d %d\n",q4.top().y,q4.top().x);
            q4.pop();
        }
        printf("\n");
    }
    return 0;
}

set会自动从小到大排序,但是很多时候需要按特定方式进行排序,所以如何自定义排序就很重要了!!!

 #include<bits/stdc++.h>
using namespace std;
struct cmp
{
    bool operator()(const string &k1,const string &k2)
    {
        return k1.length()>k2.length();
    }
};
set<string,cmp>s;
int main()
{
    s.insert("LiMin");
    s.insert("Z");
    s.insert("KKKK");
    for(set<string>::iterator it=s.begin();it!=s.end();it++)
        cout<<*it<<endl;
    return 0;
}

虽然map会自动按key值从小到大的进行排序,但是很多时候需要自定义排序方式。map按key排序挺简单,但是按value排序的话需借助vector容器,在此分别给出代码……

/*按key进行排序*/

#include<bits./stdc++.h>
using namespace std;
struct cmp
{
    bool operator()(const string &k1,const string &k2){
    return k1.length()>k2.length();
    }
};
map<string,int,cmp>m;
int main()
{
    m["LiMin"]=90;
    m["LiMi"]=79;
    m["BoB"]=92;
    for(map<string,int>::iterator it=m.begin();it!=m.end();it++)
        cout<<it->first<<' '<<it->second<<endl;
    return 0;
}

/*按value进行排序*/

#include<bits/stdc++.h>
using namespace std;
map<int,int>mp;
bool cmp(const pair<int,int>&p1,const pair<int,int>&p2)
{
    return p1.second<p2.second;
}
int main()
{
    mp[1]=4;
    mp[2]=3;
    mp[3]=2;
    mp[4]=1;
    vector<pair<int,int> >arr;
    for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++)
    {
        cout<<it->first<<' '<<it->second<<endl;
        arr.push_back(make_pair(it->first,it->second));
    }
    printf("\n\n");
    sort(arr.begin(),arr.end(),cmp);
    for(vector<pair<int,int> >::iterator it=arr.begin();it!=arr.end();it++)
        cout<<it->first<<' '<<it->second<<endl;
    return 0;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值