简体   繁体   English

基于变量的for循环的方向

[英]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? 这是宏的好用例吗?

No, doesn't sound like a good case for macros at all. 不,听起来根本不是宏的好例子。

The best (most C++-ish) thing would probably be to use a range , and pass that to the function. 最好的方法(最适合C ++)可能是使用range ,并将其传递给函数。

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.

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