2013-02-08 42 views
0

我刚刚发现这个代码实际上工作。我想知道为什么。行和列都是变量。我试图动态分配一个2D矢量。有人能解释这一点吗?谢谢!为什么这个代码可以工作

ROW和COL都是 “INT”

grid_ = new vector<vector<bool> > (row, col); 
+0

为什么你会动态分配一个二维矢量? – Rapptz 2013-02-08 19:18:56

+0

@Rapptz有什么理由不去? – JASON 2013-02-08 19:20:00

+0

这段代码甚至没有编译 – RiaD 2013-02-08 19:21:53

回答

3

有用于std::vector几个two-argument constructors。您尚未提供rowcol的类型,但我怀疑您的代码不会达到您的要求。如果你想初始化一个矢量的两个维度,你需要一个构造函数来获取初始化每个元素的大小和值。在这种情况下,该值本身就是一个向量。

int row = 5; 
std::vector<bool> col(5, false); 
grid_ = std::vector<std::vector<bool>>(row, col); 

这将初始化的bool的5x5格,全部设置为false

0

鉴于原代码

grid_ = new vector<vector<bool> > (row, col); 

其中“ rowcol都是 “INT” ”,这里’正是’ s的错:

  • 使用的vector构造函数创建一个向量row元素,初始化为col值。这是预期的可能性接近于零。

  • 向量是动态分配的,几乎不需要:vector是一个可调整大小的容器。

  • 它使用vector<bool>,这是由于它的不切实际专业化(其中每个bool可以存储为单个位,这意味着可以’吨获得对它的引用)通常避免。

相反,对于布尔值矩阵的一个好的解决方案是使用一个具有例如元素的向量。枚举类型和计算索引。


更新:检查它,代码甚至不进行编译,即在Q给出的信息是不正确

#include <vector> 
using namespace std; 

int main() 
{ 
    int row = 0; 
    int col = 0; 
    auto x = new vector<vector<bool> > (row, col); 
} 
 
[D:\dev\test] 
>g++ foo.cpp 
In file included from d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/vector:65:0, 
       from foo.cpp:1: 
d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h: In instantiation of 'void std::vector::_M_initialize_dispatch(_Integer, _Integer, std::__true_type) [with _Integer = int; _Tp = std::vector; _Alloc = std::allocat 
or >]': 
d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:393:4: required from 'std::vector::vector(_InputIterator, _InputIterator, const allocator_type&) [with _InputIterator = int; _Tp = std::vector; _Alloc = std::all 
ocator >; std::vector::allocator_type = std::allocator >]' 
foo.cpp:8:49: required from here 
d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:1137:4: error: no matching function for ca 
ll to 'std::vector >::_M_fill_initialize(std::vector >::size_type, int&)' 
d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:1137:4: note: candidate is: 
d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:1179:7: note: void std::vector::_M_fill_initialize(std::vector::size_type, const value_type&) [with _Tp = std::vector; _Alloc = std::allocator >; std::vector::size_type = unsigned int; std::vector::value_type = std::vector] 
d:\bin\mingw\bin\../lib/gcc/i686-pc-mingw32/4.7.2/../../../../include/c++/4.7.2/bits/stl_vector.h:1179:7: note: no known conversion for ar 
gument 2 from 'int' to 'const value_type& {aka const std::vector&}' 

[D:\dev\test] 
> _ 
+0

谢谢。但是如果我想将“网格”初始化为全部“假”。有没有更好的方法来做到这一点?而不是动态分配? – JASON 2013-02-08 19:37:29

+0

@anonymous downvoter:请解释您的downvote,以便其他人可以从您的洞察中受益。 – 2013-02-08 19:44:42