If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

that looks like you are shift + add, for example, if you need to hash 5 and 8, you multiply by 10 and add and it becomes 58 as a unique key, right? You can do the same with as many values as you like so long as they fit into the destination; for example, you can put 4 16 bit numbers into a 64 bit number by shifting (I prefer to just use the << and >> operators, but you can find the base 10 constant if you like, its the same result but I find shifting N bits to be easier to think about).

The problem, then, is what if you have more bits of keys than destination? You cannot fit 4 32 bit numbers into 1 64 bit number, of course, so you have to "trim" the values somehow. This is where hashing actually becomes interesting, as you must now concoct a key that is as unique as you can make it yet the potential for collisions now exists (cannot do a perfect hash now) so you also have to handle that issue.

One method that has worked well as a first cut at this problem for me is to simply use the built in random number generator against the data to make a key.
for example, if you had the 4 32 bit numbers I mentioned, and want a 16 bit key, try this:

You can play around with the srand portion based upon any knowledge you have of the keys or a bajillion other things, this is just a concept of how to use the random numbers in this manner. Of course, this implies you are doing it by hand (which I often prefer, the STL hash stuff is very heavy handed compared to simply dropping data or pointers into an array)

If you can, though, use the stl hash stuff, unless you *need* some sort of high speed setup. As I recall, the stl ones manage the keys and such for you so there is no need for the mess.

any number of integral values can be put next to each other and thought of as a sequence of bytes. and there are a number of well-known algorithms to hash a sequence of bytes: Bernstein's, FNV, Cessu, Hsieh's, and the cryptographic hashes like MD5 and SHA. it would be prudent to use a well-known algorithm that has been empirically observed to distribute hash values uniformly.

for efficient hash table look-up, the hash function should be fast, and it should cause as few collisions as possible. the algorithms that Bob Jenkins has developed are a good choice for this. http://www.burtleburtle.net/bob/hash/doobs.html

a couple of months back, i needed a function to generate a 32 bit hash from many 32 bit integers. here's the code for what it is worth - it is just a translation of Jenkins' C code http://www.burtleburtle.net/bob/c/lookup3.c into C++09.