如何在C ++ 0x中组合哈希值?

C ++ 0x添加hash<...>(...)

虽然我找不到hash_combine函数,如boost中所示 。 什么是最干净的方式来实现这样的事情? 也许,使用C ++ 0x xor_combine

那么,就像推动员工那样做:

 template <class T> inline void hash_combine(std::size_t& seed, const T& v) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); } 

我会在这里分享它,因为它可以帮助其他人寻找这个解决scheme:从@KarlvonMoor回答,这里是一个可变的模板版本,如果你需要将多个值合并在一起,

 inline void hash_combine(std::size_t& seed) { } template <typename T, typename... Rest> inline void hash_combine(std::size_t& seed, const T& v, Rest... rest) { std::hash<T> hasher; seed ^= hasher(v) + 0x9e3779b9 + (seed<<6) + (seed>>2); hash_combine(seed, rest...); } 

用法:

 std::size_t h=0; hash_combine(h, obj1, obj2, obj3); 

这是最初写的,以实现一个可变的macros来轻松地使自定义types可哈希(我认为是一个hash_combine函数的主要用法之一):

 #define MAKE_HASHABLE(type, ...) \ namespace std {\ template<> struct hash<type> {\ std::size_t operator()(const type &t) const {\ std::size_t ret = 0;\ hash_combine(ret, __VA_ARGS__);\ return ret;\ }\ };\ } 

用法:

 struct SomeHashKey { std::string key1; std::string key2; bool key3; }; MAKE_HASHABLE(SomeHashKey, t.key1, t.key2, t.key3) // now you can use SomeHashKey as key of an std::unordered_map