map按值排序

来源:互联网 发布:明天妈妈不在知乎 编辑:程序博客网 时间:2024/05/20 23:37

在STL中,map是按键来排序的,但很多时候需要按值来排序。一种方法是将map转化为vector,然后排序。(#add 此法缺点为 map内容没变,而是整个的传给vector了,之后所要用的是vector.或许也不能说是缺点.)

 另一个好的方案是 同时做一个反向的map,与之前的map,key value反过来存储.


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 itor = tMap.begin(); itor != tMap.end(); ++itor)
  {
            tVector.push_back(make_pair(itor->first,itor->second));
  }
  sort(tVector.begin(),tVector.end(),cmp);
}

 

main.cpp

 #include "tool.h"
int main()
{
   map<string,int> tMap;
   tMap["你好"]=10;
   tMap["他好"]=5;
   tMap["我好"]=15;
   vector<pair<string,int>> tVector;
   sortMapByValue(tMap,tVector);
   for(int i=0;i<tVector.size();i++)
   {
    cout<<tVector[i].first<<": "<<tVector[i].second<<endl;
   }
   system("PAUSE");
   return 0;
}

原创粉丝点击