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?
No, this is not guaranteed. std::hash
only has to respect the following conditions:
- Accepts a single parameter of type Key.
- Returns a value of type size_t that represents the hash value of the parameter.
- Does not throw exceptions when called.
- For two parameters k1 and k2 that are equal, std::hash()(k1) == std::hash()(k2).
- For two different parameters k1 and k2 that are not equal, the probability that std::hash()(k1) == std::hash()(k2) should be very small, approaching 1.0/std::numeric_limits::max().
The requirements (17.6.3.4 Hash requirements [hash.requirements]) on the value returned by a Hash
function are:
Table 26 — Hash requirements [hash]
The value returned shall depend only on the argument
k
. [ Note: Thus all evaluations of the expressionh(k)
with the same value fork
yield the same result. —end note ] [ Note: For two different valuest1
andt2
, the probability thath(t1)
andh(t2)
compare equal should be very small, approaching1.0 / numeric_limits<size_t>::max()
. —end note ]
In practice, it's quite common that for integral types std::hash(k)
would equal k
, as that is the simplest possible implementation conformant with the standard. For other types, anything is possible.
The standard only says this:
in 17.6.3.4, this is of most importance (table 26):
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.