嵌套向量的动态分配

时间:2013-02-08 18:51:19

标签: c++

我做了类似的事情:

Grid(int row, int col):num_of_row_(row), num_of_col_(col) {
     grid_ = new vector<vector<bool> > (row, col);  
}

动态分配嵌套向量。它是否正确?我的意思是使用这种语法:

new vector<vector<type> > (outersize, innersize)

其中** outersize,innersize都是“int”变量。**

更新: 我实际上使用了这个代码,它的工作原理。我只想找出原因。

1 个答案:

答案 0 :(得分:2)

传递给构造函数的第二个参数是要重复outersize次的向量的元素。您应该使用以下语法:

new vector<vector<type> > (outersize, vector<type>(innersize, elementValue));

例如,要将bool的50x25网格初始设置为true,请使用:

vector<vector<bool> > *grid = new vector<vector<bool> >(50, vector<bool>(25, true));