Using QRect with QHash

In Qt 4.3.3, I found myself needing to use QRect instances as a key in a QHash. However, Trolltech provides no qHash() implementation for QRect, so I implemented this one, and I think it ought to cover the most common uses of QRect. What do you think?

CODE:
  1. uint qHash(const QRect &rect)
  2. {
  3.     uint code = 0;
  4.  
  5.     code |= (rect.x() <<16);
  6.     code |= (rect.y() & 0x0000ffff);
  7.     code ^= (rect.width() <<16);
  8.     code ^= (rect.height() & 0x0000ffff);
  9.  
  10.     return code;
  11. }

Preliminary testing seems indicates that it produces a fairly good distribution of hash codes. In this case, I'm defining "fairly good" as, "I haven't seen any collisions on the few rectangles I've tried." :)

2 Responses to “Using QRect with QHash”

  1. Brandon Says:

    If you trust Sun you could probably use the hash implementation they use in the JVM, they usually go through a fair amount of work to ensure that they have a decent algorithm that minimizes collisions. Not sure about licensing though. Their hash is basically x + 37*y + 43*width + 47*height.

  2. Dave Says:

    Good idea! The thought didn’t occur to me. Thanks!

Leave a Reply