What should I pass to unordered_map's bucket count argument if I just want to specify a hash function?

前端 未结 2 2033
花落未央
花落未央 2021-01-07 17:42

C++11\'s unordered_map\'s default constructor looks like this:

explicit unordered_map( size_type bucket_count = /*implementation-defined*/,
             


        
2条回答
  •  春和景丽
    2021-01-07 18:26

    I wouldn't worry too much about it.

    The container guarantees the bucket count will be at least the value you provide, i.e. it will increase it if needed. You could pass zero as the bucket count and the implementation will either do something like std::max(count, 10) and override the zero value, or it will just rehash on the first insertion.

    Another alternative would be to copy the value from a default-constructed object:

    H hasher;
    unordered_map m{ unordered_map{}.bucket_count(), hasher };
    

    This will set the bucket count to whatever the implementation's default is (but does require the H hash function type to be DefaultConstructible.)

    FWIW GCC's unordered_map uses 10 as the default for the constructor you showed (so that's probably a reasonable default too) and uses 0 for the constructors taking a pair of iterators or an initializer_list.

提交回复
热议问题