1. 程式人生 > >c++中map按key和value排序

c++中map按key和value排序

algo second ios ring out 升序 i++ con pre

 1 ```
 2 #include<iostream>
 3 #include<algorithm>
 4 #include<vector>
 5 #include<map>
 6 #include<set>
 7 using namespace std;
 8 
 9 /*按key升序*/
10 void test01(){
11     map<string,int,less<string> > map1;
12     map1.insert(pair<string,int>("aba",3));
13 map1.insert(pair<string,int>("aaa",2)); 14 map1.insert(pair<string,int>("ddd",1)); 15 map1.insert(pair<string,int>("ccc",4)); 16 17 for(map<string,int>::iterator it=map1.begin(); it!=map1.end(); it++ ){ 18 cout<<(*it).first<<" : "<<(*it).second<<endl;
19 } 20 } 21 /*按key降序*/ 22 void test02(){ 23 map<string,int,greater<string> > map1; 24 map1.insert(pair<string,int>("aba",3)); 25 map1.insert(pair<string,int>("aaa",2)); 26 map1.insert(pair<string,int>("ddd",1)); 27 map1.insert(pair<string,int>("
ccc",4)); 28 29 for(map<string,int>::iterator it=map1.begin(); it!=map1.end(); it++ ){ 30 cout<<(*it).first<<" : "<<(*it).second<<endl; 31 } 32 } 33 /*----------------------------------------------------*/ 34 /*編寫類或者結構體按key升序或者降序*/ 35 class flag{ 36 public: 37 bool operator()(string v1,string v2){ 38 return v1<v2; 39 } 40 }; 41 42 void test03(){ 43 map<string,int,flag> map1; 44 map1.insert(pair<string,int>("aba",3)); 45 map1.insert(pair<string,int>("aaa",2)); 46 map1.insert(pair<string,int>("ddd",1)); 47 map1.insert(pair<string,int>("ccc",4)); 48 49 for(map<string,int>::iterator it=map1.begin(); it!=map1.end(); it++ ){ 50 cout<<(*it).first<<" : "<<(*it).second<<endl; 51 } 52 } 53 /*-------------------------------------------------------*/ 54 /*自定義編寫類或者函數或者結構體進行值排序*/ 55 /*自定義函數編寫不用(),自定義類或者結構體需要()*/ 56 bool flag_2(pair<string,int> o1,pair<string,int> o2){ 57 return o1.second>o2.second; 58 } 59 class flag_2{ 60 public: 61 bool operator()(pair<string,int> o1,pair<string,int> o2){ 62 return o1.second>o2.second; 63 } 64 }; 65 struct flag_2{ 66 bool operator()(pair<string,int> o1,pair<string,int> o2){ 67 return o1.second<o2.second; 68 } 69 }; 70 void test04(){ 71 map<string,int> map1; 72 map1.insert(pair<string,int>("aba",3)); 73 map1.insert(pair<string,int>("aaa",2)); 74 map1.insert(pair<string,int>("ddd",1)); 75 map1.insert(pair<string,int>("ccc",4)); 76 77 //利用vector進行value排序 78 vector< pair<string,int> > dic1(map1.begin(),map1.end()); 79 sort(dic1.begin(),dic1.end(),flag_2()); 80 81 for(int i=0; i<dic1.size(); i++ ){ 82 cout<<dic1[i].first<<" "<<dic1[i].second<<endl; 83 } 84 } 85 int main(){ 86 //test01(); 87 //test02(); 88 //test03(); 89 test04(); 90 91 return 0; 92 } 93 94 ```

c++中map按key和value排序