动态设置for循环的初始化、条件和in/decrementation

Dynamically set the initialization, condition, and in/decrementation of for-loops

目前,我不得不写出多个 for-loops,它们都执行相同的任务,不同之处在于初始化、条件和 [=12] 中的 de/incrementation =] 他们自己。

这里有一个类似的例子:

if(some_bool_condition)
{
    for(int i = 0; i < 5; i++)
    {
        // do something
    }
} 
else
{
    for(int i = 10; i >= 5; i--)
    {
        // do same thing
    }
}

有什么技巧或技巧可以将这些 for-loops 合并在一起吗?

让做某事成为一种功能。将起始值、测试和 increment/decrement 值作为参数传递。在函数中做for循环。

int start = 0;  // or some other value
int end   = 5;  // ditto
int delta = 1;  // 1 or -1
for ( int i = start; i != end; i += delta )
{
    // do something
}

当然,必须仔细选择增量,以便 i 实际上准确地达到 end