map按值排序
来源:互联网 发布:u盘怎么装linux系统 编辑:程序博客网 时间:2024/05/10 11:52
在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);
- }
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;
- }
0 0
- map按值排序
- map按值排序
- Map 按值排序
- map按值排序
- map按值排序
- map按值排序
- Map按值排序
- STL map 按值排序
- STL map 按值排序
- Map按值进行排序
- java Map 按值排序
- map 按键按值排序
- Map排序---按value值排序
- Map排序及HashMap按键排序和按值排序
- Map 按值排序 (Map sort by value) - Java
- Map 按值排序 (Map sort by value) - Java
- 如何对于Map类型按值排序
- 将map按值进行排序
- 1111
- 1111
- 1111
- Top 20 Best Agile Development Books, Ever
- Mongodb中插入值为空的字段
- map按值排序
- HDU 4417 Super Mario(离线线段树)
- 1111
- 什么是事务?事务的特性有哪些?
- android.app.SuperNotCalledException异常
- Ubuntu增加swap交换空间的步骤
- typeset 用法
- windows不重装系统和重建MBR分区表来扩展系统盘
- C语言内存分配图以及栈和堆的区别