Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I override std::hash?

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 ?

like image 844
user2485710 Avatar asked Aug 06 '13 11:08

user2485710


People also ask

What does std :: hash do?

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.

How do you avoid a hash collision in C++?

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.

Is STD hash unique?

Yes, std::hash return same result for different std::string . The creation of buckets is different by different compiler.

How are strings hashed in C++?

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.)


2 Answers

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

like image 112
doctorlove Avatar answered Sep 18 '22 19:09

doctorlove


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>
    {
        // ...
    };
}
like image 30
Some programmer dude Avatar answered Sep 20 '22 19:09

Some programmer dude