#include<stdio.h>
#include<string>
#include<algorithm>
#include<iostream>
#include<map>
#include<vector>
using namespace std;
//key排序的函数对象
struct CmpByKeyLength {
bool operator()(const string& k1, const string& k2) {
return k1 < k2;
}
};
typedef pair<string, int> PAIR;
//1.按值排序的比较函数
bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) {
return lhs.second > rhs.second;
}
//2.按值排序的函数对象
struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
return lhs.second > rhs.second;
}
};
//key排序
void sort_key(){
map<string, int, CmpByKeyLength> name_score_map;
name_score_map["LiMin"] = 90;
name_score_map["ZiLinMi"] = 79;
name_score_map["BoB"] = 92;
name_score_map.insert(make_pair("Bing",99));
name_score_map.insert(make_pair("Albert",86));
for (map<string, int>::iterator iter = name_score_map.begin();
iter != name_score_map.end();
++iter) {
cout<< iter->first<<" "<<iter->second << endl;
}
}
//值排序
void sort_value(){
map<string, int> name_score_map;
name_score_map["LiMin"] = 90;
name_score_map["ZiLinMi"] = 79;
name_score_map["BoB"] = 92;
name_score_map.insert(make_pair("Bing",99));
name_score_map.insert(make_pair("Albert",86));
//把map中元素转存到vector中
vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());
sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);
// sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);
for (int i = 0; i != name_score_vec.size(); ++i) {
cout<<( name_score_vec[i]).first <<" "<<( name_score_vec[i]).second<< endl;
}
}
int main(){
sort_key();
sort_value();
return 0;
}
map 按key排序和按value排序
最新推荐文章于 2024-04-16 10:44:29 发布