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 )
The While loop and the For loop are the two most common types of conditional loops in most programming languages.
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.
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.
So first the condition is checked, then the loop body is executed, then the increment.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With