2016-03-13 28 views
0

當試圖編譯代碼的g ++給了我這個錯誤:對於二維數組循環

#include<iostream> 

int main(){ 
    int coordinates[3][2]={{1,2}, 
          {5,2}, 
          {5,9}}; 
    for(int coordinate[2]:coordinates){ 
     std::cout<<coordinate[0]+coordinate[1]; 
    }; 
    return 0; 
}; 
+0

你對()循環是不正確的。你到底想要打印什麼? –

+0

我想做一個象棋遊戲和座標數組是可能的運動,這個for循環是爲了讓棋盤瓦片可能的運動。 –

回答

0

好「數組必須用括號內的初始化初始化」,我可以清楚地看到你的代碼中的問題。

在循環中,類型不是純int,而是int *。你有兩個選擇,要麼使用int *或自動

您的最終代碼看起來應該行

int main(){ 
    int coordinates[3][2]= 
    { 
     {1,2}, 
     {5,2}, 
     {5,9} 
    }; 

    // You can use either int* or auto. 
    // I personally prefer auto 
    // as it's more cleaner. 
    // 
    // for(int *coordinate :coordinates){ 


    for(auto coordinate:coordinates){ 
     std::cout<<coordinate[0]+coordinate[1]; 
    }; 
    return 0; 
}; 
+1

允許使用額外的逗號。這不是一個錯誤。 – Simple

+0

坦克你!這解決了我的問題。 –

+0

@簡單,對我來說是新的,但你是對的。謝謝 – Saleem