2016-09-28 51 views
-1

之間所以我的問題是,我要實現N代表通過以下方式循環使用代碼迴路數(其中N是一個變量):變量爲

for i0=0:MAX 
    cOR[0] = initial + move[i0]; 
     for i1=0:MAX 
      cOR[1] = cOR[0] + move[i1]; 
       .... 
       some other stuff inside the final loop 

(COR是一個向量的長度等於for循環的數量)

所以我發現這個解決方案適用於當你只有嵌套循環(https://stackoverflow.com/a/20577981/3932908),但一直在努力修改它爲我的特殊情況下需要for循環之間的代碼。有沒有一種簡單的方法來實現這一點,或者需要一種不同的方法?

+2

什麼?你不能擁有實際循環的數量(源代碼中'for'的數量)取決於某個運行時間值。 C是一種編譯語言,它不會像那樣工作。這聽起來像[XY問題](http://xyproblem.info/)。 – unwind

+2

您不能實現具有可變深度的嵌套循環。如果你真的想要,你可以有一個遞歸。 –

+0

我同意這聽起來像一個XY問題。你試圖解決什麼是真正的問題? –

回答

2

的一般方法是

  1. 寫遞歸函數。
  2. 如果遞歸不是因爲某些原因適合您的代碼(例如需要非常長的遞歸深度或需要暫停執行的能力),那麼通過顯式建模堆棧將遞歸版本轉換爲迭代版本。

做№1很簡單:

void f(int depth, int initial, int *cOR) 
{ 
    if(your termination condition) 
    { 
     // some other stuff inside the final loop, and... 
     return; 
    } 

    for(int i = 0; i < MAX; ++i) 
    { 
     cOR[depth] = initial + move[i]; 
     f(depth+1, cOR[depth]); 
    } 
} 

,並調用它像這樣:

f(0, initial, cOR); 

現在我們前往№2,即轉換成非遞歸版本。我們需要的額外狀態是之前存儲在堆棧中的值:i變量的值。所以在這裏,我們去:

int i[max_depth]; 
int depth = 0; 

for(;;) 
{ 
    if(your termination condition) 
    { 
     // some other stuff inside the final loop, and... 

     do { 
      if(--depth < 0) 
       return; 
     } while(++i[depth] >= MAX); 
    } 
    else 
     i[depth] = 0; 

    cOR[depth] = (depth > 0 ? cOR[depth-1] : initial) + move[i[depth]]; 
    ++depth; 
} 

如果無法估計max_depth先驗的,那麼你可以切換到一個動態分配的數組,生長,因爲你需要。