我剛剛發現這個代碼實際上工作。我想知道爲什麼。行和列都是變量。我試圖動態分配一個2D矢量。有人能解釋這一點嗎?謝謝!爲什麼這個代碼可以工作
ROW和COL都是 「INT」
grid_ = new vector<vector<bool> > (row, col);
我剛剛發現這個代碼實際上工作。我想知道爲什麼。行和列都是變量。我試圖動態分配一個2D矢量。有人能解釋這一點嗎?謝謝!爲什麼這個代碼可以工作
ROW和COL都是 「INT」
grid_ = new vector<vector<bool> > (row, col);
有用於std::vector
幾個two-argument constructors。您尚未提供row
和col
的類型,但我懷疑您的代碼不會達到您的要求。如果你想初始化一個矢量的兩個維度,你需要一個構造函數來獲取初始化每個元素的大小和值。在這種情況下,該值本身就是一個向量。
int row = 5;
std::vector<bool> col(5, false);
grid_ = std::vector<std::vector<bool>>(row, col);
這將初始化的bool的5x5格,全部設置爲false
。
鑑於原代碼
grid_ = new vector<vector<bool> > (row, col);
其中「 row
和col
都是 「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] > _
謝謝。但是如果我想將「網格」初始化爲全部「假」。有沒有更好的方法來做到這一點?而不是動態分配? – JASON 2013-02-08 19:37:29
@anonymous downvoter:請解釋您的downvote,以便其他人可以從您的洞察中受益。 – 2013-02-08 19:44:42
爲什麼你會動態分配一個二維矢量? – Rapptz 2013-02-08 19:18:56
@Rapptz有什麼理由不去? – JASON 2013-02-08 19:20:00
這段代碼甚至沒有編譯 – RiaD 2013-02-08 19:21:53