zl程序教程

您现在的位置是:首页 >  后端

当前栏目

(map&C++)(五、排序)sort

2023-09-27 14:26:27 时间

注意:map本身是按照key值进行升序排序,如果升序不必管理

因为sort函数对有序函数进行排序,所以需要和vector配合使用

1.对key进行降序处理

#include <bits/stdc++.h>

using namespace std;

typedef pair<string, string> PAIR;
bool cmp(const PAIR &left,const PAIR &right){
    return left.first > right.first;
}

int main(){
	map<string ,string> m;
   	m["abc"] = "456";m["def"]="789";m["ghi"]="123";
   	vector<PAIR> vec(m.begin(),m.end());
   	for(map<string,string>::iterator it = m.begin(); it != m.end(); it++){
   		cout<<it->first<<"->"<<it->second<<endl;
	}
	cout << "----------(原本升序)华丽的分割线(排序后如下)------------" << endl;
	sort(vec.begin(),vec.end(),cmp);
	for(int i = 0; i < vec.size(); i++){
		cout << vec[i].first << "->" << vec[i].second << endl;
	}



	return 0;
}

结果:

在这里插入图片描述

2.对value进行排序

#include <bits/stdc++.h>

using namespace std;

typedef pair<string, string> PAIR;
bool cmp(const PAIR &left,const PAIR &right){
    return left.second < right.second;
}

int main(){
	map<string ,string> m;
   	m["abc"] = "456";m["def"]="789";m["ghi"]="123";
   	vector<PAIR> vec(m.begin(),m.end());
   	for(map<string,string>::iterator it = m.begin(); it != m.end(); it++){
   		cout<<it->first<<"->"<<it->second<<endl;
	}
	cout << "----------(原本key升序)华丽的分割线(排序后value升序)------------" << endl;
	sort(vec.begin(),vec.end(),cmp);
	for(int i = 0; i < vec.size(); i++){
		cout << vec[i].first << "->" << vec[i].second << endl;
	}


	return 0;
}

结果:

在这里插入图片描述

3.对value进行降序就不写了(同2)