map 按key排序和按value排序

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值