2016-03-08 29 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,因为这是地方它可能会造成混淆

相关问题