小编Spo*_*ock的帖子

如何使用不同的初始值压缩多个for循环

在一个函数中,我有几个连续的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++

4
推荐指数
2
解决办法
776
查看次数

标签 统计

c++ ×1