为什么这段代码可行

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

标签: c++

我刚刚发现这段代码确实有效。我想知道为什么。 row和col都是变量。我试图动态分配2D矢量。有人可以解释一下吗?谢谢!

row和col都是“int”

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

2 个答案:

答案 0 :(得分:3)

std::vector有几个two-argument constructors。您尚未提供rowcol的类型,但我怀疑您的代码不会按预期执行。如果要在两个维度中初始化向量,则需要使用大小和值来初始化每个元素的构造函数。在这种情况下,该值本身就是一个向量。

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

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

答案 1 :(得分:0)

给出原始代码

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

其中“rowcol都是”int“”,这就是它的错误:

  • 使用的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]
> _