template<class KEY, class VALUE>
unsigned int HashMap<KEY, VALUE>::hashCode(KEY key)
{
unsigned int k = key & 0xffffffff; //error: no match for ‘operator&’ in ‘key & 4294967295u’
k += ~(k<<9);
k ^= (k>>14);
k += (k<<4);
k ^= (k>>10);
return k;
};
As you see, I’m trying to implement the hashCode by manipulating bits in the object. Obviously, bit operators don’t easily apply to user-defined objects.
I want to take some bits of an object of any type, given its memory location, and manipulate the bits as I wish. Then I’ll reinterpret the bits as int and apply bitwise operators to the int.
Does that sound like a good idea? And How can I take bits from objects of ANY TYPE at a given memory location?
Thanks a lot!
No, it’s a terrible idea, because it doesn’t respect the type’s definition of equality. A type might be defined so that several different representations can be considered equal (think of a
std::string, which contains a couple of pointers, and nothing else. Two strings might be equal (both contain"hello world", but have different pointers because they point to different blocks of memory, and so your hash key implementation would return different hash key for two equal objects.In other words, you’d break the hash table, and users would be unable to find the objects they put in the table.