If I did std::hash
using libstdc++
and then did one on the upcoming C++11
VS 2012 library - would they match?
I assume that hash implementations are not part of the C++ specification and can vary by distribution?
Yes, std::hash return same result for different std::string . The creation of buckets is different by different compiler.
The function object std::hash<> is used. Standard specializations exist for all built-in types, and some other standard library types such as std::string and std::thread .
std::hash<const char*> produces a hash of the value of the pointer (the memory address), it does not examine the contents of any character array.
The unordered_map::hash_function() is a built in function in C++ STL which is used to get the hash function. This hash function is a unary function which takes a single argument only and returns a unique value of type size_t based on it. Parameter: The function does not accept any parameter.
The standard only says this:
20.8.12 Class template hash The unordered associative containers defined in 23.5 use specializations of the class template hash as the default hash function. For all object types Key for which there exists a specialization hash, theinstantiation hash shall:
- satisfy the Hash requirements (17.6.3.4), with Key as the function call argument type, the DefaultConstructible requirements (Table 19), the CopyAssignable requirements (Table 23),
- be swappable (17.6.3.2) for lvalues,
- provide two nested types result_type and argument_type which shall be synonyms for size_t and Key, respectively,
- satisfy the requirement that if k1 == k2 is true, h(k1) == h(k2) is also true, where h is an object of type hash and k1 and k2 are objects of type Key.
in 17.6.3.4, this is of most importance (table 26):
Shall not throw exceptions. The value returned shall depend only on the argument k. [ Note: Thus all evaluations of the expression h(k) with the same value for k yield the same result. — end note ] [ Note: For two different values t1 and t2, the probability that h(t1) and h(t2) compare equal should be very small, approaching 1.0 / numeric_- limits::max(). — end note ]
So in general, no, the computation itself is not defined and the result is not required to be consistent over implementations. For that matter, even two different versions of the same library may give different results.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With