mr-edd.co.uk :: horsing around with the C++ programming language

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

(optional)
(optional)
(required, hint)

Links can be added like [this one -> http://www.mr-edd.co.uk], to my homepage.
Phrases and blocks of code can be enclosed in {{{triple braces}}}.
Any HTML markup will be escaped.