목차
1: 키(key)에 대한 맵 정렬
사실 맵에는 기본 정렬이 있는데 그 구조는 레드-블랙 트리를 사용하므로 기본 정렬은 키에 따라 정렬되고 키의 오름차순에 따라 정렬됩니다.
이러한 종류의 정렬을 사용자 정의하려면 functor를 작성하여 해결할 수 있습니다. functor가 무엇인지에 대해서는 이 문서에서 설명하지 않습니다. 이 문서에서는 사용 방법만 소개합니다(사실 제 요리입니다. 하하하 )!
(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;
}
물론 구조인 키에 대한 두 번째 정렬 방법이 있습니다.
#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: 값(값) 정렬용 맵
맵에서의 정렬은 키별 정렬을 기준으로 하므로 값을 직접 정렬할 수 없으며, 값을 정렬하려면 벡터 컨테이너와 정렬 기능을 사용해야 합니다. 물론 커스텀 정렬 규칙( imitation Function pull down이라고 함) 실제로는 템플릿 집합일 뿐입니다 .
#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;
}