您的位置:首页 > 编程语言 > C语言/C++

Map 按照Value降序排列(C++)

2015-03-11 11:40 501 查看
在使用C++中的Map时,想要对Map进行排序,而Map默认的是按照key值来排序,如果需要对Key值进行排序,则需要自己来更换一个容器,方法有很多,比较推荐的做法是使用vector***********************************************************************************************分割线**********************************************************************************1.构建一个用于比较的方法:
int cmp(const pair<string,float> &x,const pair<string,float> &y){return x.second > y.second;}
2.更换容器,并按照Value进行排列
void sortMapbyValue(map<string,float> &t_map,vector< pair<string,float> > &t_vec){for(map<string,float>::iterator iter = t_map.begin();iter != t_map.end(); iter ++){t_vec.push_back(make_pair(iter->first,iter->second));}sort(t_vec.begin(),t_vec.end(),cmp);}
3.在main 函数中调用sorMapbyValue()方法就可以实现对Map的value值排列了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: