joeButler joeButler - 1 year ago 78
C++ Question

Whats the best way to conditionally control the direction of a for loop

I've got a block in my code in which the for loop should run forwards or backwards depending on a condition.

if (forwards) {
for (unsigned x = 0; x < something.size(); x++ ) {
// Lots of code

} else {
for (unsigned x = something.size()-1 ; x >= 0 ; x-- ) {
// Lots of code

Is there a nice way to set this up, so I don't repeat all the code within the for loop twice?

The 'something' in question is a std::vector<>, so maybe its possible with an iterator?
(I'm not using C++11 )

Answer Source

Separate the loop value from the value you use inside the loop:

for (unsigned x2 = 0; x2 < something.size(); x2++ ) {
    const int x = forward ? x2 : (something.size()-1) - x2;
    // Lots of code using x
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download