Skip to main content
GameDev.net gamedev.net
🔒 Locked

c++ circular iteration

Started by Storyyeller Jun 28, 2011 at 11:16 PM 1 replies 750+ views
Original Post
Storyyeller
Storyyeller
Are there any patterns for when you need to iterate over a range but also access the next element?
For example something like this

[source lang='cpp']
std::vector v;

for(int i=0; i {
int& a = v.at(i);
int& b = v.at((i+1) % v.size());
foo(a,b);
}
[/source]

There's a lot of repetition and boilerplate code here but I can't think of any good ways to eliminate it. Boost foreach is good for regular iteration but I don't think it can do stuff like this.
I trust exceptions about as far as I can throw them.
SiCrane
SiCrane
One useful trick for these kinds of situations is putting the special case as the first iteration. Ex:

for (int i = v.size() - 1, j = 0; j < v.size(); i = j, ++j) {
foo(v, v[j]);
}
Antheus
Antheus
v.push_back(v[0]);

Problem solved.

Method is called "sentinel" and is used as alternative in example implementations of various sorting and searching algorithms.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.