Combining Hash Values in C 0x
C 0x introduced the hash<> template, which provides a generic hash function. However, a hash_combine function, as implemented in Boost, is not natively included. This article explores practical methods for implementing such a function in C 0x.
Solution using xor_combine
One approach is to leverage C 0x's xor_combine. This function combines two hash values by XORing them. Here's an example implementation:
template<class T> inline void hash_combine(std::size_t& seed, const T& v) { seed ^= hash<T>{}(v); }
This method simply XORs the hash of the value v with the seed.
Solution using Boost's hash_combine
Alternatively, you can adapt theBoost implementation of hash_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); }
This function calculates thehash of v using std::hash<> and combines it with theseed using a bitwise XOR operation.
Both approaches provide methods for combining hash values in C 0x. The choice of implementation depends on the specific requirements of the application.
The above is the detailed content of How to Efficiently Combine Hash Values in C 0x?. For more information, please follow other related articles on the PHP Chinese website!