繁体   English   中英

动态设置for循环的初始化,条件和输入/减量

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

此刻,我必须写出多个都执行相同任务的for-loops ,不同之处在于for-loops本身的初始化,条件和减少/递增。

这是到目前为止我类似的例子:

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合并在一起吗?

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

做某事是一个功能。 传递起始值,测试值和增量/减量值作为参数。 在函数中执行for循环。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM