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

xiaoxiao2021-02-28  80

  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; } 运行结果如下:

转载请注明原文地址: https://www.6miu.com/read-51954.html

最新回复(0)