1.将map转化为vector类型

2.使用sort函数对vector进行排序,写出compare比较器函数

3.比较器中指明按照第几个元素来排序

 1 #include <iostream>
 2 #include <map>
 3 #include <algorithm>
 4 #include <vector>2017-04-19
 5 using namespace std;
 6 
 7 /* run this program using the console pauser or add your own getch, system("pause") or input loop */
 8 typedef pair<string, int> PAIR;
 9 //第一种方式 
10 struct ValueSort{
11     /*
12     bool operator()(const pair<string,int> &val1,const pair<string,int> &val2) {
13         return val1.second < val2.second;
14     }
15     */
16     bool operator()(const PAIR& lhs, const PAIR& rhs) {
17     return lhs.second > rhs.second;
18   }
19 };
20 
21 //第二种方式 
22 bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) {
23   //return lhs.second < rhs.second || (lhs.second == rhs.second && lhs.first >= rhs.first);
24    return lhs.second < rhs.second;//第二个元素从小到大排序 
25 }
26 
27 int main() {
28   map<string, int> name_score_map;
29   name_score_map["LiMin"] = 90;
30   name_score_map["ZiLinMi"] = 79;
31     name_score_map["ZiLinMi"] = 90;
32   name_score_map["BoB"] = 92;
33   name_score_map.insert(make_pair("Bing",99));
34   name_score_map.insert(make_pair("Albert",86));
35   PAIR pout;
36  //把map中元素转存到vector中 
37   vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());
38   
39   sort(name_score_vec.begin(), name_score_vec.end(), cmp_by_value);//第一种 
40   //sort(name_score_vec.begin(), name_score_vec.end(), ValueSort());//第二种 
41  
42   for (int i = 0; i != name_score_vec.size(); ++i) {
43       pout = name_score_vec[i];
44     cout <<pout.first<<" "<<pout.second<<endl;
45   }
46   
47   return 0;
48 }

posted on 2016-09-14 09:23  人生一世,草木一秋。  阅读(136)  评论(0编辑  收藏  举报