什么是有条件地控制for循环方向的最佳方法

joe*_*ler 6 c++ iterator loops

我的代码中有一个块,其中for循环应该根据条件向前或向后运行.

if (forwards) {
    for (unsigned x = 0; x < something.size(); x++ ) {
        // Lots of code
    }

} else {
    for (unsigned x = something.size()-1 ; x >= 0 ; x-- ) {
        // Lots of code
    }
} 
Run Code Online (Sandbox Code Playgroud)

有没有一个很好的方法来设置它,所以我不重复两次for循环中的所有代码?

有问题的'东西'是std :: vector <>,所以也许它可以用迭代器?(我没有使用C++ 11)

Dan*_*rey 10

将循环值与循环内使用的值分开:

for (unsigned x2 = 0; x2 < something.size(); x2++ ) {
    const int x = forward ? x2 : (something.size()-1) - x2;
    // Lots of code using x
}
Run Code Online (Sandbox Code Playgroud)


Dre*_*all 6

可能最简单的方法是转换Lots of code为带参数的函数,x并用对该函数的调用替换两个循环体:

void do_lots_of_stuff(unsigned x) {
  // Lots of code
}

////////

if (forwards) {
  for (unsigned x = 0; x < something.size(); x++ ) {
    do_lots_of_stuff(x);
  }
} else {
  for (unsigned x = something.size()-1 ; x >= 0 ; x-- ) {
    do_lots_of_stuff(x);
  }
}
Run Code Online (Sandbox Code Playgroud)


Ale*_*sie 5

或者你可以这样做:

for (unsigned x = (forward ? 0: something.size()); x != (forward ? something.size() :0); forward? x++: x-- ) {
    // Lots of code
}
Run Code Online (Sandbox Code Playgroud)

编译器很可能会优化它并forward仅评估一次,因为它的值在我假设的循环中不会改变for