> I was just wondering if there is a more clever way of doing this,
Probably, but is this really your main performance bottleneck, or just a speculative guess?
Code:
[URL unfurl="true"]http://en.wikipedia.org/wiki/Optimization_(computer_science)[/URL]
Say your processor is 1GHz (probably more) and your monitor refresh rate is 100Hz (probably less). That gives you 10M instructions (at least) before your user has any chance at all of noticing what went on. Useful mouse clicking rate is more like 10Hz. You can do a lot of tests in that time.
What else are you planning to do in response to a click - redraw a bit of the screen (say a selection rectangle)?
A simple linear search may seem to be a problem on paper, but each test is only a few machine instructions. The code is obvious and easy to write.
A "better" approach (see below) is harder to write, maintain, debug etc, and has a higher overhead (like keeping the list sorted).
You could sort your list into position and size order, which would allow you to quickly reject whole sets of rectangles with a single test.
Also, since any given rectangle has a lot more outside than inside, it might be more efficient to complement the test by checking outsides rather than insides.
Code:
// rect contains left, right, bottom, top
// point contains x and y
bool pointInsideRect ( rect r, point p ) {
return r->l <= p.x &&
r->r >= p.x &&
r->b <= p.y &&
r->t >= p.y;
}
bool pointOutsideRect ( rect r, point p ) {
return r->l > p.x ||
r->r < p.x ||
r->b > p.y ||
r->t < p.y;
}
--