我的代码中有一个block,for循环应该根据条件向前或向后运行。什么是有条件地控制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)
反向迭代器。 – yngccc
使用while或do-while循环 –
请记住,在第二个for循环中'x> = 0'因为x是无符号的,所以它总是会计算真实值。 – doug