[英]Dynamically set the initialization, condition, and in/decrementation of for-loops
At the moment, I am having to write out multiple for-loops
which all do the same task, with the differences being in the initialization, condition, and the de/incrementation within the for-loops
themselves. 此刻,我必须写出多个都执行相同任务的
for-loops
,不同之处在于for-loops
本身的初始化,条件和减少/递增。
Here is an example of something similar I have so far: 这是到目前为止我类似的例子:
if(some_bool_condition)
{
for(int i = 0; i < 5; i++)
{
// do something
}
}
else
{
for(int i = 10; i >= 5; i--)
{
// do same thing
}
}
Is there a trick or technique I can use to merge these for-loops
together? 我可以使用一些技巧或技术将这些
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
}
Of course the delta has to be choosen carefully so that i
actually reaches end
exactly. 当然,必须谨慎选择三角洲,这样
i
才能准确地到达end
。
Make do someting be a function. 做某事是一个功能。 Pass the start value, test, and increment/decrement value as arguments.
传递起始值,测试值和增量/减量值作为参数。 Do the for loop in the function.
在函数中执行for循环。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.