我知道如何初始化向量1D这样如何在C++中使用构造函数初始化2D矢量?
int myints[] = {16,2,77,29};
std::vector<int> fifth(myints, myints + sizeof(myints)/sizeof(int));
假设我有2D数据。
float yy[][2] = {{20.0, 20.0}, {80.0, 80.0}, {20.0, 80.0}, {80.0, 20.0}};
如何初始化2D矢量?
我知道如何初始化向量1D这样如何在C++中使用构造函数初始化2D矢量?
int myints[] = {16,2,77,29};
std::vector<int> fifth(myints, myints + sizeof(myints)/sizeof(int));
假设我有2D数据。
float yy[][2] = {{20.0, 20.0}, {80.0, 80.0}, {20.0, 80.0}, {80.0, 20.0}};
如何初始化2D矢量?
在C++ 11可以初始化矢量的矢量是这样的:
auto yy = std::vector<std::vector<float>>
{
{20.0, 20.0},
{80.0, 80.0},
{20.0, 80.0},
{80.0, 20.0}
};
需要了解更多信息的内容包括initializer_lists和C++ 11中的统一初始化。 – YoungJohn
为什么不只是'std :: vector
@juanchopanza AAA人群再次袭击...... –
在当前的C++(自2011年),可以在构造函数中初始化这种载体:
vector<vector<float>> yy
{
{20.0, 20.0},
{80.0, 80.0},
{20.0, 80.0},
{80.0, 20.0}
};
参见它活着: http://ideone.com/GJQ5IU。
如果您事先不知道这些值,您仍然可以使用初始值初始化2D向量。
vector< vector <int> > arr(10, vector <int> (10, 0));
上述代码将初始化10X10的二维矢量,其索引值为零(0)。
请记住,矢量在内存中是连续的 –
@ Jarod42您不应该在问题中编辑OP的代码。 – herohuyongtao
@herohuyongtao:'float yy = {{..}}'是无效的。而我的编辑不会使发布的答案无效。 – Jarod42