2016-03-08 30 views
0

我目前卡住試圖使用循環的範圍基礎來初始化我的數組。如何使用基於範圍的for循環初始化2D數組爲false使用基於範圍的循環

我目前做了什麼,但它沒有在構造函數中使用C++ 11數組。構造函數是無效,不帶任何參數

//sets everything to flase 
for (size_t rowCount = 0; rowCount < NROWS; ++rowCount) { 
    for (size_t colCount = 0; colCount < NCOLS; ++colCount){ 
     m_Floor[rowCount][colCount] = STARTING_PEN_POSITION; 
    } 
} 

這裏是我迄今爲止設置應有盡有假(起始筆位置)

for (auto const &row : m_Floor) { 
    for (auto const &column : row) { 
     //something = STARTING_PEN_POSITION; 
    } 
} 

,這陣是頭文件裏面

std::array <std::array <bool, NCOLS>, NROWS> m_Floor; 

其中NCOLS是size_t的恆定靜態,值爲70

d NROWS是size_t的一個恆定值,其值爲22

+0

後'auto' .. –

+0

只是爲了確保拆除'const'之一如果我刪除它,然後使用代碼'm_Floor [row] [column] = STARTING_PEN_POSITION;'它不工作,除非我使用for循環的語法錯誤 – Aeroy

+0

你會'column = STARTING_PEN_POSITION;',而不是'm_Floor [row] [column] = STARTING_PEN_POSITION;'。或者更合理的是,你會將'column'重命名爲'cell',以明確它是對矩陣中單個單元格的引用。或者爲了簡單起見,你可以刪除內部循環,只要執行(for(auto&row:m_Floor){std :: fill(std :: begin(row),std :: end(row),STARTING_PEN_POSITION); }'。 – ShadowRanger

回答

0

我對你的問題的含義並不十分清楚,所以我會將答案發布到上面我可以看到的兩個可能的問題上。首先是爲什麼你的基於循環的範圍初始化不起作用。正如在評論中指出的,你需要刪除const。參考下面的編譯程序爲

#include <iostream> 
#include <array> 
using std::array; 
using std::cout; 
using std::endl; 

int main() { 

    array<array<int, 10>, 10> two_dimensional_array; 
    for (auto& arr : two_dimensional_array) { 
     for (auto& ele : arr) { 
      ele = 0; 
     } 
    } 

    // print all the values 
    for (auto arr : two_dimensional_array) { 
     for (auto ele : arr) { 
      cout << ele << " "; 
     } 

     cout << endl; 
    } 

    return 0; 
} 

我推斷出另一個問題是,你希望有一個很好的方式來初始化二維數組在構造函數中一行。你可以通過vector來實現這一點。它們是通常超級優化的動態數組。您可以使用vector構造函數來初始化對象。參考下面的代碼

#include <iostream> 
#include <vector> 
using std::cout; 
using std::endl; 
using std::vector; 

int main() { 

    vector<vector<int>> two_dimensional_vector (10, vector<int> (10, 5)); 
    for (auto& vec : two_dimensional_vector) { 
     for (auto ele : vec) { 
      cout << ele << " "; 
     } 

     cout << endl; 
    } 

    return 0; 
} 

請注意,我沒有用過uniform initialization syntax,因爲這是地方它可能會造成混淆

相關問題