STL中map按值排序
来源:互联网 发布:python list 遍历 编辑:程序博客网 时间:2024/05/18 20:53
map默认是按照键(key)排序的。很多时候我们需要按值(value)排序,靠map里的
算法当然是不行的,那么可以把它转存到vector中,在对vector按照一定的规则排序即可。
//示例代码:输入单词,统计单词出现次数并按照单词出现次数从多到少排序
#include <cstdlib>
#include <map>
#include <vector>
#include <string>
#include <algorithm>
#include <iostream>
void sortMapByValue(std::map<std::string, int>& tMap, std::vector<std::pair<std::string, int> >& tVector);
int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y);
int main()
{
std::map<std::string, int> tMap;
std::string word;
while (std::cin >> word)
{
std::pair<std::map<std::string, int>::iterator, bool> ret = tMap.insert(std::make_pair(word, 1));
if (!ret.second)
++ret.first->second;
}
std::vector<std::pair<std::string,int> > tVector;
sortMapByValue(tMap,tVector);
for(int i=0;i<tVector.size();i++)
{
std::cout<<tVector[i].first<<": "<<tVector[i].second<<std::endl;
}
system("pause");
return 0;
}
int cmp(const std::pair<std::string, int>& x, const std::pair<std::string, int>& y)
{
return x.second > y.second;
}
void sortMapByValue(std::map<std::string, int>& tMap, std::vector<std::pair<std::string, int> >& tVector)
{
for (std::map<std::string, int>::iterator curr = tMap.begin(); curr != tMap.end(); curr++)
{
tVector.push_back(std::make_pair(curr->first, curr->second));
}
std::sort(tVector.begin(), tVector.end(), cmp);
http://www.cnblogs.com/wanpengcoder/archive/2010/10/24/1859682.html
}
- STL中map按值排序
- STL map 按值排序
- STL map 按值排序
- stl map容器按值排序
- STL中map按值(value)排序
- STL中map按值(value)排序
- STL中map按照vaule来排序
- C++ STL中Map的相关排序操作:按Key排序和按Value排序
- STL map 按key值和按value值排序
- STL sort函数--对map按值排序
- STL sort函数--对map按值排序
- STL sort函数--对map按值排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序跟按Value排序
- C++ STL中Map的按Key排序和按Value排序
- MongoDB的安装
- hdu1394Minimum Inversion Number(线段树,求出逆序数)
- 关于引用库的问题,Actionbarsherlock和SlidingMenu
- php中session过期时间设置
- 3.16 基于OHCI的USB主机 —— 中断向量处理
- STL中map按值排序
- Qt中路径问题一般解决办法
- UIWebview
- 3.17 基于OHCI的USB主机 —— 中断处理程序
- keytool生成证书
- 110505 A multiplication game
- 修改mini2440的软MAC地址
- extjs form submit upload 返回下载download 没有回调
- 4.1 随便说几句 —— 关于USB主机系列