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

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

运行结果如下:



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值