[C++][unordered_map][无序图]2020-06-14

无序图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 mymap { {"Australia",1},{"U.S.",2},{"France",3} };
    int i = mymap["Australia"];

hash桶---bucket

image.png

因为hashable的表可能会存在冲突,内部设置了bucket的概念,每一个bucket,可能会挂载多个key。但一般不影响简单使用

#include 
#include 

int main()
{
    std::unordered_map 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

你可能感兴趣的:([C++][unordered_map][无序图]2020-06-14)