Map按照Value值排序

来源:互联网 发布:ps4最终幻想10淘宝 编辑:程序博客网 时间:2024/05/21 22:39

 

Map默认的是按照key值排序,如果需要将map按照Value值排序,需要先将Map转换成vector<pair>,然后按照pair.second的值排序即可。


bool sortByMapValue(const pair<string, int>& s1, const pair<string, int>& s2){return s1.second < s2.second;}

</pre><pre name="code" class="html"><pre name="code" class="cpp">map<string, int> test_map;test_map["b"] = 2;test_map["c"] = 1;test_map["a"] = 3;vector< pair<string, int> > sort_map(test_map.begin(), test_map.end());sort(sort_map.begin(), sort_map.end(), sortByMapValue);


                                             
0 0
原创粉丝点击