我的代码中有一个 block ,其中 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
}
}
是否有一种很好的设置方法,这样我就不会在 for 循环中重复所有代码两次?
有问题的“某物”是一个 std::vector<>,所以也许它可以用一个迭代器? (我没有使用 C++11)
最佳答案
将循环值与您在循环内使用的值分开:
for (unsigned x2 = 0; x2 < something.size(); x2++ ) {
const int x = forward ? x2 : (something.size()-1) - x2;
// Lots of code using x
}
关于c++ - 有条件地控制 for 循环方向的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19600894/