您的位置:首页 > 其它

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排序

#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;
}
}


运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: