[英]How do I combine hash values in C++0x?
Well, just do it like the boost guys did it:好吧,就像 boost 人那样做:
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);
}
I'll share it here since it can be useful to others looking for this solution: starting from @KarlvonMoor answer, here's a variadic template version, which is terser in its usage if you have to combine several values together:我将在此处分享它,因为它对寻找此解决方案的其他人很有用:从@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...);
}
Usage:用法:
std::size_t h=0;
hash_combine(h, obj1, obj2, obj3);
This was written originally to implement a variadic macro to easily make custom types hashable (which I think is one of the primary usages of a hash_combine
function):这最初是为了实现可变参数宏而编写的,以便轻松使自定义类型可散列(我认为这是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;\
}\
};\
}
Usage:用法:
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
A few days ago I came up with slightly improved version of this answer (C++ 17 support is required):几天前,我想出了这个答案的稍微改进的版本(需要 C++ 17 支持):
template <typename T, typename... Rest>
void hashCombine(uint& seed, const T& v, Rest... rest)
{
seed ^= ::qHash(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
(hashCombine(seed, rest), ...);
}
The code above is better in terms of code generation.上面的代码在代码生成方面更好。 I used qHash function from Qt in my code, but it's also possible to use any other hashers.我在我的代码中使用了 Qt 中的 qHash 函数,但也可以使用任何其他哈希器。
This could also be solved by using a variadic template as follows:这也可以通过使用可变参数模板来解决,如下所示:
#include <functional>
template <typename...> struct hash;
template<typename T>
struct hash<T>
: public std::hash<T>
{
using std::hash<T>::hash;
};
template <typename T, typename... Rest>
struct hash<T, Rest...>
{
inline std::size_t operator()(const T& v, const Rest&... rest) {
std::size_t seed = hash<Rest...>{}(rest...);
seed ^= hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
return seed;
}
};
Usage:用法:
#include <string>
int main(int,char**)
{
hash<int, float, double, std::string> hasher;
std::size_t h = hasher(1, 0.2f, 2.0, "Hello World!");
}
One could certainly make a template function, but this could cause some nasty type deduction eg hash("Hallo World!")
will calculate a hash value on the pointer rather than on the string.当然可以创建一个模板函数,但这可能会导致一些讨厌的类型推导,例如hash("Hallo World!")
将在指针上而不是在字符串上计算散列值。 This is probably the reason, why the standard uses a struct.这可能就是标准使用结构体的原因。
The answer by vt4a2h is certainly nice but uses the C++17 fold expression and not everyone is able to switch to a newer toolchain easily. vt4a2h的答案当然很好,但使用 C++17 折叠表达式,并不是每个人都能轻松切换到更新的工具链。 The version below uses the expander trick to emulate a fold expression and works in C++11 and C++14 as well.下面的版本使用扩展器技巧来模拟折叠表达式,并且也适用于C++11和C++14 。
Additionally, I marked the function inline
and use perfect forwarding for the variadic template arguments.此外,我将函数标记为inline
,并对可变参数模板参数使用完美转发。
template <typename T, typename... Rest>
inline void hashCombine(std::size_t &seed, T const &v, Rest &&... rest) {
std::hash<T> hasher;
seed ^= hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
(int[]){0, (hashCombine(seed, std::forward<Rest>(rest)), 0)...};
}
I really like the C++17 approach from the answer by vt4a2h , however it suffers from a problem: The Rest
is passed on by value whereas it would be more desirable to pass them on by const references (which is a must if it shall be usable with move-only types).我真的很喜欢vt4a2h的答案中的 C++17 方法,但是它遇到了一个问题: Rest
是按值传递的,而通过 const 引用传递它们会更可取(如果需要,这是必须的)可用于仅移动类型)。
Here is the adapted version which still uses a fold expression (which is the reason why it requires C++17 or above) and uses std::hash
(instead of the Qt hash function):这是仍然使用折叠表达式(这就是它需要 C++17 或更高版本的原因)并使用std::hash
(而不是 Qt 哈希函数)的改编版本:
template <typename T, typename... Rest>
void hash_combine(std::size_t& seed, const T& v, const Rest&... rest)
{
seed ^= std::hash<T>{}(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
(hash_combine(seed, rest), ...);
}
For completeness sake: All the types which shall be usable with this version of hash_combine
must have a template specialization for hash
injected into the std
namespace.为完整起见:所有可用于此版本hash_combine
必须具有注入std
命名空间的hash
模板特化。
Example:例子:
namespace std // Inject hash for B into std::
{
template<> struct hash<B>
{
std::size_t operator()(B const& b) const noexcept
{
std::size_t h = 0;
cgb::hash_combine(h, b.firstMember, b.secondMember, b.andSoOn);
return h;
}
};
}
So that type B
in the example above is also usable within another type A
, like the following usage example shows:因此,上面示例中的类型B
也可以在另一个类型A
,如下面的用法示例所示:
struct A
{
std::string mString;
int mInt;
B mB;
B* mPointer;
}
namespace std // Inject hash for A into std::
{
template<> struct hash<A>
{
std::size_t operator()(A const& a) const noexcept
{
std::size_t h = 0;
cgb::hash_combine(h,
a.mString,
a.mInt,
a.mB, // calls the template specialization from above for B
a.mPointer // does not call the template specialization but one for pointers from the standard template library
);
return h;
}
};
}
You can use the rst C++ library that I developed to do that:您可以使用我开发的第一个C++ 库来做到这一点:
#include "rst/stl/hash.h"
struct Point {
Point(const int x, const int y) : x(x), y(y) {}
int x = 0;
int y = 0;
};
bool operator==(const Point lhs, const Point rhs) {
return (lhs.x == rhs.x) && (lhs.y == rhs.y);
}
namespace std {
template <>
struct hash<Point> {
size_t operator()(const Point point) const {
return rst::HashCombine({point.x, point.y});
}
};
}
The answer by Henri Menke works great, but if you treat warnings as errors with for example: Henri Menke的答案很有效,但如果您将警告视为错误,例如:
add_compile_options(-Werror)
GCC 9.3.0 will give this error: GCC 9.3.0 会出现这个错误:
Test.h:223:67: error: ISO C++ forbids compound-literals [-Werror=pedantic]
223 | (int[]){0, (hashCombine(seed, std::forward<Rest>(rest)), 0)...};
| ^
cc1plus: all warnings being treated as errors
We can update the code to avoid the error like this:我们可以更新代码来避免这样的错误:
template <typename T, typename... Rest>
inline void hashCombine(std::size_t &seed, T const &v, Rest &&... rest) {
std::hash<T> hasher;
seed ^= (hasher(v) + 0x9e3779b9 + (seed << 6) + (seed >> 2));
int i[] = { 0, (hashCombine(seed, std::forward<Rest>(rest)), 0)... };
(void)(i);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.