如果我只想指定哈希函数,应将什么传递给unordered_map的存储区计数参数? [英] What should I pass to unordered_map's bucket count argument if I just want to specify a hash function?

查看:101
本文介绍了如果我只想指定哈希函数,应将什么传递给unordered_map的存储区计数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++ 11的 unordered_map 的默认构造函数如下:

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() );

我想创建一个 unordered_map 自定义的哈希函数,但这是构造函数的第二个参数。

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?

推荐答案

我不会为此担心太多。

该容器保证存储区计数至少为您提供的值 ,即,如果需要,它将增加该值。您可以传递零作为存储区计数,并且实现将执行类似 std :: max(count,10)的操作并覆盖零值,否则它将重新哈希

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 };

这会将存储区计数设置为实现的默认值(但确实需要 H 哈希函数类型为DefaultConstructible。)

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的 unordered_map 使用10作为显示的构造函数的默认值(因此这也可能是一个合理的默认值),对于采用一对迭代器或 initializer_list 的构造函数使用0。

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.

这篇关于如果我只想指定哈希函数,应将什么传递给unordered_map的存储区计数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆