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

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。