C++中的map排序

目录

1:map对于key(键)的排序

2:map对于value(值)的排序


1:map对于key(键)的排序

map中其实是有默认排序的,它里面的构造是用到红黑树,所以它的默认排序是按照键来排序的,并且是按照键的升序来排序的。

我们如果想要对这种排序进行自定义的话,可以通过自己写一个仿函数来解决,至于什么是仿函数,本篇文章不做解释,本篇文章只介绍怎么用(其实是我菜,哈哈哈)!

(1)map中的key的默认排序

#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)对于key的自定义排序

#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)key是结构体的排序

#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:map对于value(值)排序

在map中的排序是基于按照key来排序的,所以无法对value直接进行排序,如果想对value进行排序,需要用到vector容器以及sort函数,当然了还有自定义的排序规则(就叫仿函数拉倒),其实也是一套模板而已

#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;
}

猜你喜欢

转载自blog.csdn.net/gaoqiandr/article/details/127172792
今日推荐