[英]Direction of for loop based on variable
I have a couple of biggish for loops which I would like to separate into functions to reduce code duplication. 我有一些for循环功能,我想分成几个函数来减少代码重复。
The only difference between them is the first line of the loop. 它们之间的唯一区别是循环的第一行。
One is: 一种是:
for (int j = 50; j < average_diff; j++) {
The other is: 另一个是:
for (int j = upper_limit; j > lower_limit; j--) {
I have an integer, tb which indicates which one I'd like to use (it has a value of 1 or 2 respectively). 我有一个整数tb,它指示我要使用哪个整数(其值分别为1或2)。
I'm wondering how I might best accomplish this. 我想知道如何才能最好地做到这一点。 Is this a good use case for macros?
这是宏的好用例吗?
Don't wrap the for
, just wrap the contents in a function: 不要包装
for
,只需将内容包装在函数中:
for (int j = 50; j < average_diff; j++) {
process(j);
}
for (int j = upper_limit; j > lower_limit; j--) {
process(j);
}
If your variable is, like you say, 1
for one direction and 2
for another, you can use the ternary operator ?:
: 如果你的变量是,像你说的,
1
为一个方向, 2
为另一个,你可以使用三元运算符?:
for (int i = (dir == 1 ? 0 : 20);
dir == 1 ? i < upper_limit :
i > lower_limit;
i += (dir == 1 ? 1 : -1))
{
...
}
However, it might be more readable if you just use a simple if
statement: 但是,如果仅使用简单的
if
语句,则可能更易读:
if (dir == 1)
{
for (int i = 0; i < upper_limit; i++)
{
}
}
else
{
for (int i = 20; i > lower_limit; i--)
{
}
}
If you go with the last, then I suggest you put the code inside the loop in a separate function that you call, so you don't have any duplicate code. 如果您使用的是最后一个,那么我建议您将代码放在循环中的一个单独函数中,以进行调用,这样就不会有重复的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.