STL中map按值(value)排序
2010-11-06 14:45
323 查看
文中的部分内容参考自互联网,感谢作者。
map默认是按照键(key)排序的。很多时候我们需要按值(value)排序,靠map里的
算法当然是不行的,那么可以把它转存到vector中,在对vector按照一定的规则排序即可。
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); }
相关文章推荐
- C++ STL中Map的按Key排序和按Value排序
- [收藏]C++ STL中Map的按Key排序和按Value排序
- 动态规划(1) 编程题#2: 滑雪(C++ STL中Map的按Key排序和按Value排序,memset函数直接将数组中的元素全部置成某个数,常函数)
- C++ STL中Map的按Key排序和按Value排序
- STL中map按值(value)排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- STL中map按值(value)排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- C++ STL中Map的按Key排序和按Value排序
- Map按照Value值进行排序
- STL之unordered_map map multimap 排序 嵌套
- 对Map按key和value分别排序
- C++按map的value进行排序
- Map排序——按key排序,按value排序
- Java Map按键(Key)排序和按值(Value)排序
- java Map 之 排序(key,value)
- map如何按value来排序------用带pair的vector吧