标准容器没有std :: hash的特化吗?

时间:2011-11-06 13:41:44

标签: c++ arrays c++11 hash-function unordered-set

just发现自己因为无法简单地使用

而感到有些惊讶
std::unordered_set<std::array<int, 16> > test;

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

我真的觉得这应该成为标准库的一部分。

2 个答案:

答案 0 :(得分: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*>;

答案 1 :(得分:11)

我不确定为什么标准库没有包含它,但是Boost已经散列了各种由hashable类型组成的东西。关键功能是hash_combine,欢迎您从boost/functional/hash/hash.hpp复制。

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