您的位置:首页 > 其它

在STL中,map按值来排序的实现方法_永不言弃是生命的基调!_百度空间

2012-07-19 23:28 746 查看
在STL中,map按值来排序的实现方法_永不言弃是生命的基调!_百度空间

在STL中,map按值来排序的实现方法

在STL中,map是按键来排序的,但很多时候需要按值来排序。一种方法是将map转化为vector,然后排序。

tool.h

#ifndef TOOL_H
#define TOOL_H
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector);
#endif

tool.cpp

#include "tool.h"
int cmp(const pair<string,int>& x,const pair<string,int>& y)
{
return x.second<y.second;
}
void sortMapByValue(map<string,int>& tMap,vector<pair<string,int>>& tVector)
{
for(map<string,int>::iterator curr=tMap.begin();curr!=tMap.end();curr++)
{
tVector.push_back(make_pair(curr->first,curr->second));
}
sort(tVector.begin(),tVector.end(),cmp);
}

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