分享

(C++)STL中map按照vaule来排序

 大道至简o 2014-09-23

  STL中map结构实际运用时,有时需要我们通过<key,value>中的value来进行排序而不是使用默认的key,由于value值是有可能重复的,所以交换key和value不一定达到要求。这里我们可以通过使用vector来实现这一转换:

  1 把map结构中的数据放到vector中

  2 设置vector的排序算法来实现通过value排序

 

代码如下:

 18 #include<iostream>
 19 #include<string>
 20 #include<string.h>
 21 #include<map>
 22 #include<vector>
 23 #include<algorithm>
 24
 25 using namespace std;
 26
 27 int cmp(const pair<string,double> &x,const pair<string,double> &y)
 28 {
 29     return x.second > y.second;
 30 }
 31
 32 void sortMapbyValue(map<string,double> &t_map,vector< pair<string,double> > &t_vec)
 33 {
 34     for(map<string,double>::iterator iter = t_map.begin();iter != t_map.end(); iter ++)
 35     {
 36         t_vec.push_back(make_pair(iter->first,iter->second));
 37     }
 38
 39     sort(t_vec.begin(),t_vec.end(),cmp);
 40 }
 41
 42 int main(void)
 43 {
 44     map<string,double> m_result;
 45     vector< pair<string,double> > v_result;
 46
 47     m_result.insert(pair<string,double>("abc",20.33));
 48     m_result.insert(pair<string,double>("abd",22.33));
 49     m_result.insert(pair<string,double>("abe",21.33));
 50     m_result.insert(pair<string,double>("abf",19.33));
 51
 52     cout<<"sort by key :"<<endl<<endl;
 53     for(map<string,double>::iterator iter = m_result.begin(); iter != m_result.end(); iter++)
 54     {
 55         cout<<iter->first<<"\t\t"<<iter->second<<endl;
 56     }
 57
 58     sortMapbyValue(m_result,v_result);
 59
 60     cout<<"sort by value :"<<endl<<endl;
 61     for(int i=0; i<v_result.size(); i++)
 62     {
 63         cout<<v_result[i].first<<"\t\t"<<v_result[i].second<<endl;
 64     }
 65
 66 }

运行结果:

 

(C++)STL中map按照vaule来排序

 

参考: http://blog.csdn.net/wanpengcoder/article/details/5991792

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多