5

For a simple C++ struct that has three ints to identify a unique structure, what can be a good hash function implementation if not too much is known about the realistic values of a,b and c. I need to use the struct as Key to unordered_map?

struct Key {

        int a, b, c;

    }
Saher Ahwal
  • 9,015
  • 32
  • 84
  • 152
  • 4
    Does it matter really that much? You could try something like `long h = (a * 10079 + b * 20047) ^ ( c *30089 );` or whatever you want.... – Basile Starynkevitch Feb 11 '14 at 20:28
  • 1
    What do you mean by "good"? What is the balance you are trying to achieve with regards to speed vs number of collisions? – emsworth Feb 11 '14 at 20:36
  • by good I meant balanced. Since I have no information about the int attributes – Saher Ahwal Feb 11 '14 at 20:42
  • Depending on what compiler you use, this is not necessary. GCC for example has an implementation of `unordered_map` that is pretty much insensitive to bad input. Otherwise, using a simple multiply-add-xor mix as proposed by @BasileStarynkevitch is a quite good hash for the short input. More sophisticated hash functions don't perform significantly better on short input (in particular functions with ridiculously large block and digest sizes such as MD5 do not). Hashing 96 bits input into a 128bit digest is a bad approach (since you will only be using a subset of that, you'll throw away entropy). – Damon Feb 11 '14 at 21:48
  • Any hash table is only as good as your hashing function. You simply can't make an implementation of `unordered_map` that performs well if your hashing function generates tons of collisions. It will degrade to linked-list levels of performance. – StilesCrisis Feb 12 '14 at 00:51

1 Answers1

1

Pass the entire struct to Murmurhash: https://sites.google.com/site/murmurhash/

Don't try to mix the values yourself (e.g. the advice above to multiply, add, xor, etc). The whole point of leveraging a hash function is that it can already mix them very effectively. If you pre-mix, you're just taking away useful entropy.

StilesCrisis
  • 15,972
  • 4
  • 39
  • 62