为了支持用户定义的键类型,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;
std::unordered_set<X>
仅使用type的默认哈希编写会更方便X
,例如编译器和库附带的类型。咨询后
- C++ 标准草案 N3242 §20.8.12 [unord.hash] 和 §17.6.3.4 [hash.requirements],
- Boost.Unordered
- 克++
include\c++\4.7.0\bits\functional_hash.h
- VC10
include\xfunctional
- 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——,这些是我的问题:
将这样的专业化添加到命名空间是否合法
std
?我对此有复杂的感觉。哪个
std::hash<X>::operator()
版本(如果有)符合 C++11 标准?有便携的方法吗?