Iteration from 1..n or n..1 conditionally in C ++

I have some code that looks something like this:

bool var = some condition...
if( var )
{
     for( int i=0; i<10; ++i )
     {
         //execute some code ...
     }
}
else
{
     for( int i=9; i>=0; --i )
     {
         //execute some other code...
     }
}

However, the code that must be executed inside the for loop is almost identical, so I don’t want to write it twice. I know I can do something like this:

bool var = some condition...
for( int i = (var ? 0 : 9 ); (var ? i<10 : i>=0 ); (var ? ++i : --i ) )
{
    //Execute my code
}

But this is really not an elegant solution.

Is there a short, more elegant way to do this? I checked std :: iterator, but I don't think what I need.

+4
source share
5 answers

Here you focus on the wrong issue. If you have a direction flag, don't make all the hang on the iteration variable be literally correct. Just interpret it as needed:

for (int i = 0; i < n; ++i)
{
   int j = var ? i : n - 1 - i;

   // j goes from 0..n-1 or n-1..0
}

, .

+3

/ . this, . , .

++ 11, , , ( ). , , .

, , ? , , , / 1..n abs . , .

+3

, , . , . , , .

bool var = some condition...
int start = 0;
int end = 9;
int increment = 1;
if (!var)
{
    // Reverse direction
    start = 9;
    end = 0;
    increment = -1;
}

// Loop (forwards if var; reversed if !var)
for (int i = start; i != end; i += increment)
{
} 
+2

- .

for(int j = 0; j < 10; ++j) { // always increases
    int i = var ? j : 10 - 1 - j;
    //go
}
+1

This looks suspiciously like an iteration to me, so try writing a function that helps us:

void incr(int& i) { ++i; }
void decr(int& i) { --i; }

template <typename Iter, typename Incr>
void do_work(Iter start, Iter finish, Incr incr)
{
    for(Iter i = start, i != finish; incr(i))
    {
        // Do your code.
    }
}

bool var = some condition...
if( var )
{
    do_work(0, 10, &incr);
}
else
{
    do_work(9, -1, &decr);
}
+1
source

Source: https://habr.com/ru/post/1538105/


All Articles