标准容器没有 std::hash 的专门化吗?
我只是发现自己有点惊讶无法简单地使用 a,
std::unordered_set<std::array<int, 16> > test;
因为似乎没有针对 std::array
的 std::hash
专门化。这是为什么?或者我根本就没有找到它?如果确实没有,下面的实现尝试是否可以简化?
namespace std
{
template<typename T, size_t N>
struct hash<array<T, N> >
{
typedef array<T, N> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a) const
{
hash<T> hasher;
result_type h = 0;
for (result_type i = 0; i < N; ++i)
{
h = h * 31 + hasher(a[i]);
}
return h;
}
};
}
我真的觉得这应该成为标准库的一部分。
I just found myself a little bit surprised being unable to simply use a
std::unordered_set<std::array<int, 16> > test;
because there does not seem to be a std::hash
specialization for std::array
s. Why is that? Or did I simply not find it? If there is indeed none, can the following implementation attempt be simplified?
namespace std
{
template<typename T, size_t N>
struct hash<array<T, N> >
{
typedef array<T, N> argument_type;
typedef size_t result_type;
result_type operator()(const argument_type& a) const
{
hash<T> hasher;
result_type h = 0;
for (result_type i = 0; i < N; ++i)
{
h = h * 31 + hasher(a[i]);
}
return h;
}
};
}
I really feel this should somehow be part of the standard library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不是答案,而是一些有用的信息。 C++11 标准的 2 月草案指定
std::hash
专门用于以下类型:error_code
§ 19.5.5bitset
代码> § 20.5.3unique_ptr
§ 20.7.2.36shared_ptr
§ 20.7.2.36type_index
§ 20.13.4字符串
§ 21.6u16string
§ 21.6u32string
§ 21.6wstring
§ 21.6向量
§ 23.3.8thread::id
§ 30.3.1.1以及所有这些类型: § 20.8.12
Not an answer, but some useful information. The Feb draft of the C++11 standard specifies that
std::hash
is specialized for these types:error_code
§ 19.5.5bitset<N>
§ 20.5.3unique_ptr<T, D>
§ 20.7.2.36shared_ptr<T, D>
§ 20.7.2.36type_index
§ 20.13.4string
§ 21.6u16string
§ 21.6u32string
§ 21.6wstring
§ 21.6vector<bool, Allocator>
§ 23.3.8thread::id
§ 30.3.1.1And all these types: § 20.8.12
我不确定为什么标准库没有包含这个,但是 Boost 对由可哈希类型组成的各种事物进行了哈希处理。其关键函数是
hash_combine
,欢迎您从boost/function/hash/hash.hpp
复制该函数。使用
hash_combine
,Boost 派生出range_hash
(仅组合范围中每个元素的哈希值)以及对和元组哈希器。range_hash
又可用于散列任何可迭代容器。I'm not sure why the standard library hasn't included this, but Boost has hashing for all sorts of things made up from hashable types. The key function for this is
hash_combine
, which you are welcome to copy fromboost/functional/hash/hash.hpp
.Using
hash_combine
, Boost derives arange_hash
(just combining the hashes of a each element of a range), as well as pair and tuple hashers. Therange_hash
in turn can be used to hash any iterable container.