为了支持用户定义的键类型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,就像编译器和库中的类型一样.咨询后
include\c++\4.7.0\bits\functional_hash.h include\xfunctional似乎可以专门化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)