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

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

原文地址:https://www.cnblogs.com/lexus/p/2600271.html