错误的对的int的哈希函数 [英] error for hash function of pair of ints

查看:271
本文介绍了错误的对的int的哈希函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 unordered_map 成员和一个为对定义的散列函数的类

I have the following class with an unordered_map member, and a hash function defined for pair<int,int>

class abc
{public :
    unordered_map < pair<int,int> , int > rules ;
    unsigned nodes;
    unsigned packet ;     
};

namespace std {
template <>
    class hash < std::pair< int,int> >{
    public :
        size_t operator()(const pair< int, int> &x ) const
        {
            size_t h =   std::hash<int>()(x.first) ^ std::hash<int>()(x.second);
            return  h ;
        }
    };
}

但我遇到以下错误:

error: invalid use of incomplete type ‘struct std::hash<std::pair<int, int> >

error: declaration of ‘struct std::hash<std::pair<int, int> >

error: type ‘std::__detail::_Hashtable_ebo_helper<1, std::hash<std::pair<int, int> >, true>’ is not a direct base of ‘std::__detail::_Hash_code_base<std::pair<int, int>, std::pair<const std::pair<int, int>, int>, std::__detail::_Select1st, std::hash<std::pair<int, int> >, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, true>’


推荐答案

不幸的是,这个程序有未定义的行为。 C ++ 11§17.6.4.2.1:

Unfortunately, this program has undefined behavior. C++11 §17.6.4.2.1:


程序可以将任何标准库模板的模板专门化添加到命名空间std声明取决于用户定义的类型,并且专业化满足原始模板的标准库要求,并且没有明确禁止。

A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

hash< pair< int,int>> 仅取决于原始和标准库类型。通过在命名空间 std 之外定义哈希类,并在地图声明中明确使用该哈希:

hash<pair<int,int>> depends on primitive and standard library types only. This is easily worked around by defining your hash class outside of namespace std, and using that hash explicitly in your map declaration:

struct pairhash {
public:
  template <typename T, typename U>
  std::size_t operator()(const std::pair<T, U> &x) const
  {
    return std::hash<T>()(x.first) ^ std::hash<U>()(x.second);
  }
};

class abc {
  std::unordered_map<std::pair<int,int>, int, pairhash> rules;
};

编辑:我使用xor在这里组合对成员的哈希,因为我懒惰,但严重使用 xor是一个相当糟糕的哈希组合函数

I've used xor to combine the hashes of the pair members here because I'm lazy, but for serious use xor is a fairly crappy hash combining function.

这篇关于错误的对的int的哈希函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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