27

只是发现自己有点惊讶不能简单地使用

std::unordered_set<std::array<int, 16> > test;

因为似乎没有 s 的std::hash专业化std::array。这是为什么?还是我根本没找到?如果确实没有,是否可以简化以下实现尝试?

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

我真的觉得这应该以某种方式成为标准库的一部分。

4

2 回答 2

12

不是答案,而是一些有用的信息。C++11 标准的 2 月草案指定std::hash专用于这些类型:

  • error_code§ 19.5.5
  • bitset<N>§ 20.5.3
  • unique_ptr<T, D>§ 20.7.2.36
  • shared_ptr<T, D>§ 20.7.2.36
  • type_index§ 20.13.4
  • string§ 21.6
  • u16string§ 21.6
  • u32string§ 21.6
  • wstring§ 21.6
  • vector<bool, Allocator>§ 23.3.8
  • thread::id§ 30.3.1.1

以及所有这些类型:§ 20.8.12

template <> struct hash<bool>;
template <> struct hash<char>;
template <> struct hash<signed char>;
template <> struct hash<unsigned char>;
template <> struct hash<char16_t>;
template <> struct hash<char32_t>;
template <> struct hash<wchar_t>;
template <> struct hash<short>;
template <> struct hash<unsigned short>;
template <> struct hash<int>;
template <> struct hash<unsigned int>;
template <> struct hash<long>;
template <> struct hash<long long>;
template <> struct hash<unsigned long>;
template <> struct hash<unsigned long long>;
template <> struct hash<float>;
template <> struct hash<double>;
template <> struct hash<long double>;
template<class T> struct hash<T*>;
于 2012-01-06T22:07:53.743 回答
11

我不确定为什么标准库没有包含这个,但是 Boost 对由可散列类型组成的各种事物都有散列。其关键功能是hash_combine,欢迎您复制boost/functional/hash/hash.hpp

使用hash_combine,Boost 派生 a range_hash(仅组合范围内每个元素的散列),以及对和元组散列器。反过来range_hash可以用来散列任何可迭代的容器。

于 2011-11-06T16:34:01.353 回答