Is there a way to repeat a loop cycle?

Viewed 171

Is there a way to repeat a loop cycle like in code example below, without i incrementing by 1?

bool twice = true;
bool* repeated = new bool[64];
int counter = 0;
for (int i = 0; i < 64; i++)
{
    counter++;
    if (twice && !repeated[i])
    {
       repeated[i] = true;
       repeat;
    }
}
delete[] repeated;
cout << counter << endl;
//counter should print 128

Edit: All iterations need to be repeated.

2 Answers

You could use a lambda function to wrap the interior of your loop and then simply call it twice.

bool twice = true;
int counter = 0;
auto execute_interior = [](const int i){/*Do something with i*/};

for (int i = 0; i < 64; i++)
{
    ++counter;

    execute_interior(i);
    if (twice)
        execute_interior(i);
}

std::cout << counter << std::endl;

Edit: I moved the counter out of the lambda as it seems it should not be in the repeated part of the code.

I asked you whether all iterations needed to be repeated and you answered in the affirmative.

I also asked whether it was important to do one pass or whether two passes would be acceptable. If it's the latter, then I will bluntly recommend that you not try to be too smart. Go with the obvious:

/* Count the widgets twice: */
for (int i = 0; i != 2; ++i)
{
    for (int j = 0; j != 64; ++j)
        do_something();
}

If you absolutely need a single pass, then my suggestion would be just as simple, and along the lines of what @StefanKssmr already gave you and I'll add an extra comment to avoid some conscientious programmer from breaking the code down the line by removing the apparently erroneous duplication:

for (int i = 0; i != 64; ++i)
{
    /* This call is duplicated on purpose! */
    do_something();
    do_something();
}

If you need to pass the index of the iteration into do_something there's a bit of a dirty trick that you can do:

for (int i = 0; i != 128; ++i)
    do_something(i / 2);

With all that said, I will caution you: your example likely doesn't describe the issue you're having accurately; rather it describes a very abstract implementation of a solution you've come up with and it may be that in not asking the actual question you have, you're getting locked into a bad design choice.

Related