目次
1:キー(キー)のマップソート
実際、マップにはデフォルトのソートがあり、その構造は赤黒ツリーを使用しているため、デフォルトのソートはキーに従ってソートされ、キーの昇順に従ってソートされます。
この種のソートをカスタマイズしたい場合は、ファンクターを作成することで解決できます. ファンクターが何であるかについては、この記事では説明しません. この記事では、使用方法のみを紹介します (実際には私の料理です, ハハハ)!
(1) マップ内のキーのデフォルトの並べ替え
#include<bits/stdc++.h>
using namespace std;
//对于map中的key的默认排序
map<int,string>m;
int main()
{
m[1]="iui";
m[87]="sjddd";
m[2]="jsd";
m[67]="yuuuu";
for(auto it=m.begin();it!=m.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
(2) キーのカスタムソート
#include<bits/stdc++.h>
using namespace std;
//对于map中的key进行paixu
struct rule{
bool operator()(string a,string b){
return a>b;//对于键是string型按照从大到小排
}
};
int main()
{
//map中的第三个参数其实就是排序规则,之前不写就会默认成默认排序
map<string,int,rule>m;
m["asas"]=199;
m["zx"]=99;
m["gsgus"]=878;
m["yuy"]=1515;
map<string,int,rule>::iterator it;
for(it=m.begin();it!=m.end();it++){
cout<<it->first<<" "<<it->second<<endl;
}
return 0;
}
(3) 鍵は構造のソート
#include<bits/stdc++.h>
using namespace std;
//按照键是结构体的排序
typedef struct{
string name;
int score;
}node;
struct rule{
bool operator()(node a,node b){
if(a.score==b.score){
return a.name>b.name;
}
return a.score>b.score;
}
//排序规则是按照成绩大的在前面,相同按照名字降序
};
int main()
{
node stu;
map<node,int,rule>m;
stu.name="abc";
stu.score=88;
m[stu]=1212;
stu.name="acd";
stu.score=88;
m[stu]=1213;
stu.name="bcbc";
stu.score=100;
m[stu]=1214;
stu.name="zzzzzz";
stu.score=1000;
m[stu]=8989;
map<node,int,rule>::iterator it;
for(it=m.begin();it!=m.end();it++){
cout<<"名字="<<it->first.name<<" 成绩="<<it->first.score<<" 学号="<<it->second<<endl;
}
return 0;
}
もちろん、構造体であるキーには 2 つ目のソート方法があります。
#include<bits/stdc++.h>
using namespace std;
//对于键是结构体的自定义排序
typedef struct node{
int score;
string name;
bool operator <(const node &s)const{
if(score!=s.score)return score>s.score;
return name>s.name;
}
}node;
int main()
{
map<node,int>m;
node u;
u.name="abc";
u.score=99;
m[u]=12;
u.name="bcd";
u.score=99;
m[u]=13;
u.name="bbb";
u.score=100;
m[u]=14;
u.name="yuy";
u.score=15;
m[u]=6666;
map<node,int>::iterator it;
for(it=m.begin();it!=m.end();it++){
cout<<"成绩="<<it->first.score<<" 名字="<<it->first.name<<" 学号="<<it->second<<endl;
}
return 0;
}
2: 値 (値) の並べ替えのマップ
マップでのソートはキーによるソートに基づいているため、値を直接ソートすることはできません.値をソートしたい場合は、ベクターコンテナとソート機能を使用する必要があります.もちろん、カスタムソートルールもあります(模倣関数プルダウンと呼ばれます)、実際には、単なるテンプレートのセットです。
#include<bits/stdc++.h>
using namespace std;
//map中对于value排序
//之前说的map是个键值对,所以需要vector
//来接收的话,那么就需要一对一,就需要用到pair了
bool cmp(const pair<string,int> a,pair<string,int>b){
return a.second>b.second;
}
int main()
{
map<string,int>m;
m["asas"]=18;
m["ioio"]=90;
m["cj"]=89;
vector<pair<string,int>>v(m.begin(),m.end());
sort(v.begin(),v.end(),cmp);
map<string,int>::iterator it;
for(int i=0;i<v.size();i++){
cout<<v[i].first<<" "<<v[i].second<<endl;
}
return 0;
}