相关疑难解决方法(0)

如何在无序容器中为用户定义的类型专门化std :: hash <Key> :: operator()?

为了支持用户定义的键类型std::unordered_set<Key>std::unordered_map<Key, Value> 一个具有提供operator==(Key, Key)和散列函子:

struct X { int id; /* ... */ };
bool operator==(X a, X b) { return a.id == b.id; }

struct MyHash {
  size_t operator()(const X& x) const { return std::hash<int>()(x.id); }
};

std::unordered_set<X, MyHash> s;
Run Code Online (Sandbox Code Playgroud)

std::unordered_set<X> 使用类型的默认哈希来编写会更方便X,就像编译器和库中的类型一样.咨询后

似乎可以专门化std::hash<X>::operator():

namespace std { // argh!
  template <>
  inline size_t 
  hash<X>::operator()(const X& x) const { return …
Run Code Online (Sandbox Code Playgroud)

c++ hash unordered-map unordered-set c++11

95
推荐指数
2
解决办法
5万
查看次数

用户定义类的哈希函数.如何交朋友?:)

我有一个C类,它有一个string* ps私有数据成员.
现在,我想要一个unordered_map<C, int>我需要自定义哈希函数的东西.

根据c ++参考,我可以这样做

namespace std {
  template<>
  class hash<C> {
  public:
    size_t operator()(const C &c) const
    {
      return std::hash<std::string>()(*c.ps);
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

问题是,我似乎无法operator()C朋友交往,以便我可以访问ps.

我试过这个:

class C;
template<>
class std::hash<C>;
class C{
  //...
  friend std::hash<C>::operator ()(const C&) const; // error: Incomplete type 
};
// define hash<C> here.
Run Code Online (Sandbox Code Playgroud)

但它说嵌套名称说明符中的不完整类型...

我也无法扭转这些定义,因为如果后来定义了C类,hash<C>则无法知道ps.

我在这做错了什么?如何在不ps公开的情况下解决这种情况?

c++ hash unordered-map c++11

13
推荐指数
1
解决办法
7560
查看次数

标签 统计

c++ ×2

c++11 ×2

hash ×2

unordered-map ×2

unordered-set ×1