首页 > 编程知识 正文

冒泡排序c程序,map按照key排序

时间:2023-05-06 17:55:46 阅读:270098 作者:1990



首先,得说明,在c++中有两个关联容器,第一种是map,内部是按照key排序的,第二种是unordered_map,容器内部是无序的,使用hash组织内容的。
对有序map中的key排序如果在有序的map中,key是int,或者string,它们天然就能比较大小,本身的就是有序的。不用额外的操作。
如果map中的key是自定义类型呢?

#include<iostream>#include <stdio.h>#include<string> #include<map> using namespace::std;typedef pair<string, int> PAIR;struct CmpByKeyLength {bool operator()(const string& k1, const string& k2) {return k1.length() < k2.length();}};int main() { map<string, int, CmpByKeyLength > name_score_map;name_score_map["LiMin"] = 90;name_score_map["ZiLinMi"] = 79;name_score_map["BoB"] = 92;name_score_map.insert(make_pair("Bing", 99));name_score_map.insert(make_pair("Albert", 86));for (map<string, int>::iterator iter = name_score_map.begin();iter != name_score_map.end();++iter) {cout<< iter->first << "t" << iter->second<<endl;}getchar();}

按照上面的代码其实是运行不了的。
报下面的错误
 error C3848: 具有类型“const CmpByKeyLength”的表达式会丢失一些 const-volatile 限定符以调用“bool CmpByKeyLength::operator ()(const std::string &,const std::string &)”
 CmpByKeyLength里面得加上const!

具体的说,代码如下:

struct CmpByKeyLength {bool operator()(const string& k1, const string& k2) const {return k1.length() < k2.length();}};
上面的代码是按照key的长度排序,这个知道了,那对key进行任何操作就都OK的。


对无序的map按照value排序#include<iostream>#include <stdio.h>#include<string> #include<unordered_map>#include <algorithm>using namespace::std;typedef pair<string, int> PAIR;struct CmpByValue {bool operator()(const PAIR& k1, const PAIR& k2)const {return k1.second > k2.second;}};int main() { unordered_map<string, int> name_score_map;name_score_map["LiMin"] = 90;name_score_map["ZiLinMi"] = 79;name_score_map["BoB"] = 92;name_score_map.insert(make_pair("Bing", 99));name_score_map.insert(make_pair("Albert", 86));//遍历hash tablefor(const auto& iter:name_score_map)cout << iter.first << "t" << iter.second << endl;cout << 'abc' << endl;vector<PAIR> name_score_vec(name_score_map.begin(), name_score_map.end());sort(name_score_vec.begin(), name_score_vec.end(), CmpByValue());for (int i = 0; i != name_score_vec.size(); ++i) {cout << name_score_vec[i].first << "t" << name_score_vec[i].second<<endl;}getchar();}对value排序还有更简单的方法
int main(){ unordered_map<int, int> iMap; iMap[1] = 20; iMap[2] = 10; iMap[5] = 30; iMap[4] = 0; vector<pair<int, int>> vtMap; for (auto it = iMap.begin(); it != iMap.end(); it++) vtMap.push_back(make_pair(it->first, it->second)); sort(vtMap.begin(), vtMap.end(), [](const pair<int, int> &x, const pair<int, int> &y) -> int { return x.second < y.second; }); for (auto it = vtMap.begin(); it != vtMap.end(); it++) cout << it->first << ':' << it->second << 'n'; return 0;}

参考资料http://blog.csdn.net/acidgl8757/article/details/17416439
http://blog.csdn.net/theonegis/article/details/48549887



版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。