依map的value进行排序时,不能直接使用sort函数,这是因为map存储的是pair元素,不是线性而无法直接排序。在此,其中一种方法就是将map中的key与value存入vector中的pair类型之中。
实现对pair按value进行比较(通过比较函数或者函数对象)
typedef pair<string, int> PAIR;
bool cmp_by_value(const PAIR& lhs, const PAIR& rhs) {
return lhs.second < rhs.second;
}
struct CmpByValue {
bool operator()(const PAIR& lhs, const PAIR& rhs) {
return lhs.second < rhs.second;
}
};
实现函数
int main() {
map<string, int> 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<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());
sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());
// 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] << endl;
}
return 0;
}
除此之外,我们还可以构造新的map,将原map的key与value作为value与key插入新的map中,这样自然会得到依value而有序的序列了