在STL中,map按值来排序的实现方法_永不言弃是生命的基调!_百度空间
2012-07-19 23:28
746 查看
在STL中,map按值来排序的实现方法_永不言弃是生命的基调!_百度空间
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);
}
在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);
}
相关文章推荐
- 在STL中,map按值来排序的实现方法
- 在STL中,map按值来排序的实现方法
- Java 对Map进行排序的实现方法
- STL中map,multimap,set,multiset,unordered_map,unordered_multimap,unordered_set,unordered_multiset的实现方法
- Java实现对map或hashmap排序的三种方法或思路
- Java Map 按照Value排序的实现方法
- 常见排序的原理和C++实现(一)——STL库中sort的使用方法
- 实现TreeSet排序和遍历map的方法
- Java Map 按key排序和按Value排序的实现方法
- 多种方法实现。递归算法和标准函数库(STL)实现全排列+sort在全排列前的排序
- java Collections.sort()实现List排序的默认方法和自定义方法
- Python实现二维数组按照某行或列排序的方法【numpy lexsort】
- 用仿函数实现以std::string作为key的map自定义排序
- 合并两个已排序的链表(递归方法实现)
- 1.4 map实现并行处理方法
- Map.Entry 类使用简介,为Map中值排序的方法
- Java实现几种常见排序方法
- PHP编程实现多维数组按照某个键值排序的方法小结【2种方法】
- Map和Stack的STL方法简介
- STL之map实现(四)