I can replace the actual implementation of std::hash
with my own definition of std::hash
in C++ 11 ?
I mean from my codebase, without touching the standard library.
I can't see any use for virtual function/polymorphism in this case, so I suppose that I can't alter the definition of std::hash anyway ?
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.
It's not possible to avoid collisions with a hash. If you have no collisions then you don't have a hashing function. The goal is to minimize collisions, not eliminate them. You'll always have contention unless you have more possible hashes than possible inputs, which sort of defeats the point of hashing.
Yes, std::hash return same result for different std::string . The creation of buckets is different by different compiler.
The hash code for a String object is computed as s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)
You can specialise hash for specific types. See here and here e.g. like this
namespace std {
template <> struct hash<Foo>
{
size_t operator()(const Foo & x) const
{
/* your code here, e.g. "return hash<int>()(x.value);" */
}
};
}
If you think you can do better than the library implementors for existing versions you are either 1. wrong or 2. clever
Yes it's okay, and you don't have to modify the standard library in any way, just use template specialization:
namespace std
{
template<>
struct hash<YourSpecialType>
{
// ...
};
}
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