无序图unordered_map
基本概念
是一种hash图。
key是用于identity value。
key和value的类型可以不一样。
value是无序的。
相比于map,它从key找value的速度更快,但在range iteration的时候效率更低。
每个value的key都不能相同。
first is key, second is value
根据key来找value是合理的,但不能反过来!
比如:
unordered_map<string,int> mymap { {"Australia",1},{"U.S.",2},{"France",3} };
int i = mymap["Australia"];
hash桶---bucket
因为hashable的表可能会存在冲突,内部设置了bucket的概念,每一个bucket,可能会挂载多个key。但一般不影响简单使用
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<std::string, std::string> mymap;
mymap = { {"Australia","Canberra"},{"U.S.","Washington"},{"France","Paris"} };
std::cout << "mymap contains:";
for (auto it = mymap.begin(); it != mymap.end(); ++it)
std::cout << " " << it->first << ":" << it->second;
std::cout << std::endl;
std::cout << "mymap's buckets contain:\n";
for (unsigned i = 0; i < mymap.bucket_count(); ++i) {
std::cout << "bucket #" << i << " contains:";
for (auto local_it = mymap.begin(i); local_it != mymap.end(i); ++local_it)
std::cout << " " << local_it->first << ":" << local_it->second;
std::cout << std::endl;
}
return 0;
}
它的bucket结构是:
bucket #0 contains:
bucket #1 contains: Australia:Canberra
bucket #2 contains: France:Paris
bucket #3 contains:
bucket #4 contains:
bucket #5 contains:
bucket #6 contains:
bucket #7 contains: U.S.:Washington