有序容器(map,multimap,set,multiset),關鍵字類型必須定義元素比較方法。默認狀況下,標準庫使用關鍵字類型的<運算來比較兩個關鍵字。ios
關鍵字類型重載了<運算符:數據結構
using std::endl;app using std::map;函數 using std::string;this
struct Student{spa unsigned int age;ci string name;string Student(unsigned int _age, string _name){hash this->age = _age;it 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; } |
爲何有序容器的關鍵字類型有嚴格弱序的要求?得從實現的STL來分析。map的STL實現是基於紅黑樹的數據結構。當使用迭代器遍歷有序容器時,迭代器按照關鍵字的升序遍歷元素。
無序容器不是使用比較運算來組織元素,而是使用一個hash function和關鍵字類型的==運算符。在關鍵字類型的元素沒有明顯的序關係的狀況下,無序容器是很是有用的。
#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; } |