关联容器的Key
Posted sunnypoem
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关联容器的Key相关的知识,希望对你有一定的参考价值。
有序容器关键字类型要求
有序容器(map,multimap,set,multiset),关键字类型必须定义元素比较方法。默认情况下,标准库使用关键字类型的<运算来比较两个关键字。
关键字类型重载了<运算符:
using std::endl; using std::map; using std::string;
struct Student{ unsigned int age; string name; Student(unsigned int _age, string _name){ this->age = _age; this->name = _name; } bool operator<(const Student &B)const; };
bool Student::operator<(const Student &B)const{ return (this->age < B.age) || (this->age == B.age && this->name < B.name); }
map<Student,string> mapStudents;
int main() { mapStudents[Student(4, "Alpha")] = string("Alpha"); mapStudents[Student(3, "Bob")] = string("Bob"); mapStudents[Student(3, "Alex")] = string("Alex"); for (auto it = mapStudents.begin(); it != mapStudents.end();++it ){ cout<<it->second.c_str()<<endl; } return 0; } |
定义两个关键字的<的比较运算函数:
#include <iostream> #include <map> #include <string>
using namespace std; using std::cout; using std::endl; using std::map; using std::string;
struct Student{ unsigned int age; string name; Student(unsigned int _age, string _name){ this->age = _age; this->name = _name; } };
struct studentOrder{ bool operator()(const Student &A, const Student &B){ return (A.age < B.age) || (A.age == B.age && A.name < B.name); } };
map<Student,string, studentOrder> mapStudents;
int main() { mapStudents[Student(4, "Alpha")] = string("Alpha"); mapStudents[Student(3, "Bob")] = string("Bob"); mapStudents[Student(3, "Alex")] = string("Alex"); for (auto it = mapStudents.begin(); it != mapStudents.end();++it ){ cout<<it->second.c_str()<<endl; } return 0; } |
map的STL
为什么有序容器的关键字类型有严格弱序的要求?得从实现的STL来分析。map的STL实现是基于红黑树的数据结构。当使用迭代器遍历有序容器时,迭代器按照关键字的升序遍历元素。
红黑树
无序容器的关键字类型要求
无序容器不是使用比较运算来组织元素,而是使用一个hash function和关键字类型的==运算符。在关键字类型的元素没有明显的序关系的情况下,无序容器是非常有用的。
unordered_map的hash函数
#include <iostream> #include <unordered_map> #include <string>
using namespace std; using std::cout; using std::endl; using std::unordered_map; using std::string;
struct AppServer { int id; string svrName;
AppServer(unsigned int _id, string name) { id = _id; svrName = name; }
bool operator==(const AppServer &other) const { return ((id == other.id) && (svrName == other.svrName)); } };
namespace std { template <> struct hash<AppServer> { size_t operator()(const AppServer& app) const { return hash<int>()(app.id); } }; }
unordered_map<AppServer,string> svrOwner;
int main() { svrOwner.insert({AppServer(4, string("LBS")), string("Ali")}); svrOwner.insert({AppServer(2, string("MT")), string("Baidu")}); svrOwner.insert({AppServer(1, string("MAP")), string("Google")}); for (auto it = svrOwner.begin(); it != svrOwner.end();++it ){ cout<<it->second.c_str()<<endl; }
return 0; } |
桶大小
以上是关于关联容器的Key的主要内容,如果未能解决你的问题,请参考以下文章