通过重载operator()从自己的类型获取unordered_map失败

Exp*_*ob1 3 c++

operator()内部(哈希器)出了什么问题Entity

将其复制粘贴到单独的struct作品中:

#include <bitset>
#include <unordered_map>
using namespace std;

struct Entity {
  
  string name;
  
  size_t operator()(const Entity& k) const noexcept 
  { return std::hash<string>{}(k.name); }
  
  bool operator== (const Entity& e) const noexcept 
  { return e.name == name; }

};

struct KeyHasher {
  size_t operator()(const Entity& k) const noexcept
  { return std::hash<string>{}(k.name); }
};

int main(){
 // unordered_map<const Entity, bitset<24>, KeyHasher> m1; // OK
 unordered_map<const Entity, bitset<24>> m2; // unordered_map() ill-formed ?
  return 0;
}
Run Code Online (Sandbox Code Playgroud)

错误 :

<source>: In function 'int main()':
<source>:25:43: error: use of deleted function 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() 
[with _Key = const Entity; _Tp = std::bitset<24>; _Hash = std::hash<const Entity>; _Pred = std::equal_to<const Entity>; _Alloc = std::allocator<std::pair<const Entity, std::bitset<24> > >]'
   25 |   unordered_map<const Entity, bitset<24>> m2;
      |                                           ^~
In file included from /opt/compiler-explorer/gcc-cxx-modules-trunk-20220427/include/c++/11.0.0/unordered_map:47,
                 from <source>:3:
/opt/compiler-explorer/gcc-cxx-modules-trunk-20220427/include/c++/11.0.0/bits/unordered_map.h:141:7: note: 'std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map() [with _Key = const Entity; _Tp = std::bitset<24>; _Hash = std::hash<const Entity>; _Pred = std::equal_to<const Entity>; _Alloc = std::allocator<std::pair<const Entity, std::bitset<24> > >]'
 is implicitly deleted because the default definition would be ill-formed:
  141 |       unordered_map() = default;
Run Code Online (Sandbox Code Playgroud)

跑步

Vla*_*eel 5

如果您没有为映射指定哈希函数,它将默认使用std::hash<Key>您的键类型。所以你需要定义这个专业化std::hash

template<>
struct std::hash<const Entity>
{
    std::size_t operator()(const Entity const& k) const noexcept
    {
        return std::hash<string>{}(k.name);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • @ExpertNoob1 `operator()` 需要位于一个单独的结构中,然后您可以将其指定为哈希器。不在您存储在那里的班级中。至于“unordered_set”,您指定了“bitset&lt;24&gt;”作为散列器(这是无效的,但只有当您尝试在那里插入某些内容时似乎才会中断)。 (2认同)