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

耗尽温柔 提交于 2019-11-30 21:37:52

问题


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

explicit unordered_map( size_type bucket_count = /*implementation-defined*/,
                    const hasher& hash = hasher(),
                    const key_equal& equal = key_equal(),
                    const allocator_type& alloc = allocator_type() );

I want to create an unordered_map with a custom hasher function, but it's the second argument to the constructor.

What bucket count should I use? Is there a magic value I can use to tell the container to decide for itself? Otherwise, is there a heuristic I can use to guesstimate a good bucket number based on something like the number of keys I expect my map to contain? Should I even care?


回答1:


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<K,T,H,P> m{ unordered_map<K,T,H,P>{}.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.




回答2:


One of the template parameters for unordered_map is the hash function. If you specify your hash function object there you can leave the constructor parameters at their default settings.



来源:https://stackoverflow.com/questions/14179441/what-should-i-pass-to-unordered-maps-bucket-count-argument-if-i-just-want-to-sp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!