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 }
运行结果:
参考: http://blog.csdn.net/wanpengcoder/article/details/5991792
|