目的:map[key, value],按照value排序
一、加头文件 #include<algorithm>
二、加入代码
typedef pair<string, int> PAIR;
int cmp(const PAIR& x, const PAIR& y){
return x.second > y.second;
}vector<PAIR> pair_vec;
for(map<string,int>::iterator map_iter = name.begin();map_iter!=name.end();++map_iter){
pair_vec.push_back(make_pair(map_iter->first, map_iter->second));
}
sort(pair_vec.begin(), pair_vec.end(),cmp);for(vector<PAIR>::iterator curr = pair_vec.begin(); curr!=pair_vec.end(); ++curr){
cout<<curr->second<<''<<curr->second<<endl;
}
本文介绍了一种使用C++标准模板库(STL)中的map和vector容器配合sort函数实现根据map容器中元素的value值进行排序的方法。通过定义一个比较函数cmp来比较value值的大小,并将map中的元素复制到vector容器中进行排序。
667

被折叠的 条评论
为什么被折叠?



