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

来源:互联网 发布:验血公司theranos知乎 编辑:程序博客网 时间:2024/06/06 16:49

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

  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(){map<string,double> m_result;vector< pair<string,double> > v_result;m_result.insert(pair<string,double>("AAA", 20.33));m_result.insert(pair<string,double>("BBB", 22.33));m_result.insert(pair<string,double>("CCC", 21.33));m_result.insert(pair<string,double>("DDD", 19.33));m_result.insert(pair<string,double>("EEE", 22.33));cout<<"sort by key :"<<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<<endl<<"sort by value :"<<endl;for(int i=0; i<v_result.size(); i++){cout<<v_result[i].first<<"\t\t"<<v_result[i].second<<endl;}return 0;}

运行结果如下: