정렬 된 키워드 형 용기 요구 사항
정렬 된 용기 (지도 multimap에, 세트는 MULTISET ) 의 키워드 타입은 비교 방법의 요소를 정의한다. 기본적으로 라이브러리의 표준 키 유형 < 작업은 두 개의 키워드를 비교합니다.
키워드를 입력 과부하 < 연산자를 :
표준 : ENDL를 사용하여; 표준 : :지도를 사용하여; 표준 : : 문자열을 사용하여;
구조체 학생 { 서명되지 않은 INT 나이; 문자열 이름; 학생 (서명 INT _age, 문자열 _name) { this-> 연령 = _age; this-> 이름 _name =; } 불리언 연산자 <(CONST 학생 & B) CONST; };
불리언 연산자 학생 :: <(CONST 학생 & B) {CONST 리턴 (this-> 세 <B.age) || (this-> 연령 == B.age && this-> 이름 <B.name); }
지도 <학생, 문자열> mapStudents;
() 주요 int로 { mapStudents [학생 (4 "알파") = 문자열 ( "알파"); mapStudents [학생 (3, "밥") = 문자열 ( "밥"); 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; } |
桶大小