Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 )

like image 785
joeButler Avatar asked Oct 25 '13 23:10

joeButler


People also ask

Is for loop conditional?

The While loop and the For loop are the two most common types of conditional loops in most programming languages.

Does for loop run only when the condition is true?

A for loop works as long as the condition is true. The flow of control, at first comes to the declaration, then checks the condition. If the condition is true, then it executes the statements in the scope of the loop. At last, the control comes to the iterative statements and again checks the condition.

Can for loop take two conditions?

It do says that only one condition is allowed in a for loop, however you can add multiple conditions in for loop by using logical operators to connect them.

Which order is correct for a for loop?

So first the condition is checked, then the loop body is executed, then the increment.


1 Answers

Or you can do something like this:

for (unsigned x = (forward ? 0: something.size()); x != (forward ? something.size() :0); forward? x++: x-- ) {
    // Lots of code
}

The compiler will most likely optimize it and evaluate forward only once since it's value doesn't change in the for loop I assume.

like image 53
Alexandru Barbarosie Avatar answered Sep 19 '22 15:09

Alexandru Barbarosie