Neat trick: iterating over consecutive pairs of adjacent indices
[9th February 2010]
Serving up a somewhat daft post today, but it's nice to bump in to stuff like this now and again; one of those things that you come across and say Huh! How the smeg have I not seen that before?
.
Well, maybe you've seen it, but it's new to me.
Suppose we have an array of points representing a polygon. To iterate over the (implied) edges of said polygon:
vector<vec3> polygon = get_the_polygon();
size_t polysize = polygon.size();
for (size_t i = polysize-1, j = 0; j != polysize; i = j, j++)
{
// edge joins polygon[i] to polygon[j]
}
Whenever I've had to write loops like this in the past, I've always ended up using arithmetic modulo polysize to get the other index:
vector<vec3> polygon = get_the_polygon();
size_t polysize = polygon.size();
for (size_t i = 0; i != polysize; i++)
{
const size_t j = (i+1) % polysize;
// edge joins polygon[i] to polygon[j]
}
I've always thought that to be a little bit yucky. Doing polysize-1 CRAZY EXPENSIVE modulo operations plagues the optimization-focused mind, I guess! The other thing I've done in the past is to pull out the last edge as a special case, which is of course JUST GHASTLY.
Comments
All original content copyright© Edd Dawson.
All source code appearing on this website that was written by Edd Dawson is made available under the terms of the Boost software license version 1.0 unless otherwise stated or implied by the license associated with the work from which the code is derived.
