STL中map按值(value)排序

STL中map按值(value)排序 - wanpengcoder - 博客频道 - CSDN.NET


STL中map按值(value)排序


分类:
C/C++


912人阅读
评论(0)
收藏
举报

 

 

文中的部分内容参考自互联网,感谢作者。

 

map默认是按照键(key)排序的。很多时候我们需要按值(value)排序,靠map里的

算法当然是不行的,那么可以把它转存到vector中,在对vector按照一定的规则排序即可。

 

[cpp:showcolumns] view plain copy print ?
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······150
  1. //示例代码:输入单词,统计单词出现次数并按照单词出现次数从多到少排序  
  2. #include <cstdlib>  
  3. #include <map>  
  4. #include <vector>  
  5. #include <string>  
  6. #include <algorithm>  
  7. #include <iostream>  
  8.    
  9. void sortMapByValue(std::map<std::string, int>& tMap, std::vector<std::pair<std::string, int> >& tVector);  
  10. int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y);  
  11.    
  12. int main()  
  13. {  
  14.  std::map<std::string, int> tMap;  
  15.  std::string word;  
  16.  while (std::cin >> word)  
  17.  {  
  18.  std::pair<std::map<std::string, int>::iterator, bool> ret = tMap.insert(std::make_pair(word, 1));  
  19.  if (!ret.second)  
  20.  ++ret.first->second;  
  21.  }   
  22.    
  23.  std::vector<std::pair<std::string,int> > tVector;  
  24.  sortMapByValue(tMap,tVector);  
  25.  for(int i=0;i<tVector.size();i++)  
  26.  {  
  27.     std::cout<<tVector[i].first<<": "<<tVector[i].second<<std::endl;  
  28.  }    
  29.    
  30.  system("pause");  
  31.  return 0;  
  32. }  
  33.    
  34. int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y)  
  35. {  
  36.  return x.second > y.second;  
  37. }  
  38.    
  39. void sortMapByValue(std::map<std::string, int>& tMap, std::vector<std::pair<std::string, int> >& tVector)  
  40. {  
  41.  for (std::map<std::string, int>::iterator curr = tMap.begin(); curr != tMap.end(); curr++)  
  42.  {  
  43.  tVector.push_back(std::make_pair(curr->first, curr->second));  
  44.  }  
  45.    
  46.  std::sort(tVector.begin(), tVector.end(), cmp);  
  47. }  
posted on 2012-07-23 11:41  lexus 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/lexus/archive/2012/07/23/2604704.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值