如何专门化std :: hash< Key> :: operator()用于无序容器中的用户定义类型? [英] How to specialize std::hash<Key>::operator() for user-defined type in unordered containers?

查看:172
本文介绍了如何专门化std :: hash< Key> :: operator()用于无序容器中的用户定义类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

支持 std :: unordered_set< Key> std :: unordered_map< Key,Value>
一个必须提供运算符==(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;

这将是更方便的写 std :: unordered_set< X&
,类型为 X ,默认值为 编译器和库。
咨询后

It would be more convenient to write just std::unordered_set<X> with a default hash for type X, like for types coming along with the compiler and library. After consulting

  • C++ Standard Draft N3242 §20.8.12 [unord.hash] and §17.6.3.4 [hash.requirements],
  • Boost.Unordered
  • g++ include\c++\4.7.0\bits\functional_hash.h
  • VC10 include\xfunctional
  • various related questions in Stack Overflow

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

namespace std { // argh!
  template <>
  inline size_t 
  hash<X>::operator()(const X& x) const { return hash<int>()(x.id); } // works for MS VC10, but not for g++
  // or
  // hash<X>::operator()(X x) const { return hash<int>()(x.id); }     // works for g++ 4.7, but not for VC10 
}                                                                             

C ++ 11尚未实验---我没有试过Clang ---,这是我的问题:

Given compiler support for C++11 is yet experimental---I did not try Clang---, these are my questions:


  1. 它合法添加这样的专业到命名空间 std ?我有这种混合的感觉。

  1. Is it legal to add such a specialization to namespace std? I have mixed feelings about that.

std :: hash< X> :: operator()版本

是否有可移植的方式?


推荐答案

明确允许并鼓励您向命名空间添加特殊化 std *。添加散列函数的正确方法是(和基本上只有):

You are expressly allowed and encouraged to add specializations to namespace std*. The correct (and basically only) way to add a hash function is this:

namespace std {
  template <> struct hash<Foo>
  {
    size_t operator()(const Foo & x) const
    {
      /* your code here, e.g. "return hash<int>()(x.value);" */
    }
  };
}

(您可能会考虑支持的其他流行专业化是 std :: less 和 std :: swap

(Other popular specializations that you might consider supporting are std::less, std::equal_to and std::swap.)

*)只要一个涉及的类型是用户定义的,我想。

这篇关于如何专门化std :: hash&lt; Key&gt; :: operator()用于无序容器中的用户定义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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