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);