STL中map按照vaule来排序
2015-07-02 14:37
603 查看
map默认是按照键(key)排序的。很多时候我们需要按值(value)排序,靠map里的算法当然是不行的,STL中map结构实际运用时,有时需要我们通过<key,value>中的value来进行排序而不是使用默认的key,由于value值是有可能重复的,所以交换key和value不一定达到要求。这里我们可以通过使用vector来实现这一转换:
1 把map结构中的数据放到vector中
2 设置vector的排序算法来实现通过value排序
运行结果:
1 把map结构中的数据放到vector中
2 设置vector的排序算法来实现通过value排序
#include<iostream> #include<string> #include<string.h> #include<map> #include<vector> #include<algorithm> using namespace std; int cmp(const pair<string,double> &x,const pair<string,double> &y) { return x.second > y.second; } void sortMapbyValue(map<string,double> &t_map,vector< pair<string,double> > &t_vec) { for(map<string,double>::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); } int main(void) { map<string,double> m_result; vector< pair<string,double> > v_result; m_result.insert(pair<string,double>("abc",20.33)); m_result.insert(pair<string,double>("abd",22.33)); m_result.insert(pair<string,double>("abe",21.33)); m_result.insert(pair<string,double>("abf",19.33)); cout<<"sort by key :"<<endl<<endl; for(map<string,double>::iterator iter = m_result.begin(); iter != m_result.end(); iter++) { cout<<iter->first<<"\t\t"<<iter->second<<endl; } sortMapbyValue(m_result,v_result); cout<<"sort by value :"<<endl<<endl; for(int i=0; i<v_result.size(); i++) { cout<<v_result[i].first<<"\t\t"<<v_result[i].second<<endl; } }
运行结果:
相关文章推荐
- ios 提交
- Laravel5.1学习笔记17 数据库3 数据迁移
- bootstrap之辅助类
- JFinal最简单demo + gradle
- 【Java基础学习笔记】Thread+JLabel实现线程
- spring 注解扫描bean配置
- [iOS]使用Audio Queue Services 播放和录制音频
- (最新版)百度地图§覆盖物OverlayOptions
- PL/SQL精明的调用栈分析
- [android警告]AndroidManifest.xml警告 Not targeting the latest versions of Android
- mac下彻底卸载mysql方法
- js获取服务器生成并返回客户端呈现给客户的控件id的方法
- Laravel5.1学习笔记16 数据库2 查询构造器(这个不用看,不如用EloquentORM)
- 2015.7.2 想做T再次失败
- android的Broadcast receiver
- Winform开发之DataGridView的增删改
- 从linux主目录中的makefile文件分析编译构成。。。
- 动态规划
- 解决Mac下GDB提示签名错误
- foreache里加事件