map按值排序

 

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

tool.h

view plaincopy to clipboardprint?

  1. #ifndef TOOL_H
  2. #define TOOL_H
  3. #include
  4. #include
  5. #include
  6. #include
  7. #include
  8. using namespace std; 
  9. void sortMapByValue(map& tMap,vector>& tVector); 
  10. #endif

tool.cpp

view plaincopy to clipboardprint?

  1. #include "tool.h"
  2. int cmp(const pair& x,const pair& y) 
  3. return x.second
  4. void sortMapByValue(map& tMap,vector>& tVector) 
  5. for(map::iterator curr=tMap.begin();curr!=tMap.end();curr++) 
  6.      { 
  7.         tVector.push_back(make_pair(curr->first,curr->second)); 
  8.      } 
  9.      sort(tVector.begin(),tVector.end(),cmp); 

main.cpp

view plaincopy to clipboardprint?

  1. #include "tool.h"
  2. int main() 
  3.    map tMap; 
  4.    tMap["你好"]=10; 
  5.    tMap["他好"]=5; 
  6.    tMap["我好"]=15; 
  7.    vector> tVector; 
  8.    sortMapByValue(tMap,tVector); 
  9. for(int i=0;i
  10.    { 
  11.        cout<<<": "<<
  12.    } 
  13.    system("PAUSE"); 
  14. return 0; 

来自:

http://blog.csdn.net/andyelvis/archive/2009/07/19/4361962.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值