在一个函数中,我有几个连续的for循环,它们具有相同的代码,但控制变量的初始值不同.初始值是从函数的输入获得的.也就是说,
void thisFunction( class A a){
//some other code
for (int i = a.x; i != 0; --i){
code
}
for (int i = a.y; i != 0; --i){
code
}
for (int i = a.z; i != 0; --i){
code
}
//some other code
}
Run Code Online (Sandbox Code Playgroud)
有没有办法将所有for循环压缩到一个循环中,这样当我在循环中更改代码时,我不必为所有三个循环更改它?另一种方法是使用初始值作为输入编写anotherFunction(),但我需要访问thisFunction()中的局部变量.
void anotherFunction(int in){
for (int i = in; i != 0; --i){
code
}
}
Run Code Online (Sandbox Code Playgroud)
那么还有另一种方法可以压缩循环吗?
谢谢.
c++ ×1