map 按key排序和按value排序

#include
#include 
#include
#include
#include
#include
using namespace std;


//key排序的函数对象 
struct CmpByKeyLength {  
  bool operator()(const string& k1, const string& k2) {  
    return k1 < k2;  
  }  
}; 

typedef pair 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 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::iterator iter = name_score_map.begin();  
       iter != name_score_map.end();  
       ++iter) {  
    	cout<< iter->first<<"   "<second << endl;  
  	}  
}
//值排序 
void sort_value(){
	map 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 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;
}

你可能感兴趣的:(stl)