[英]How to fill `std::vector<std::vector<T> >` with default values?
So I try this: 所以我试试这个:
std::vector< std::vector<int> > matrix(4);
matrix[0][0] = 1;
matrix[0][1] = 2;
matrix[0][2] = 3;
matrix[0][3] = 1;
matrix[1][0] = 1;
matrix[1][1] = 2;
matrix[1][2] = 3;
matrix[1][3] = 1;
matrix[2][0] = 1;
matrix[2][1] = 2;
matrix[2][2] = 3;
matrix[2][3] = 1;
matrix[3][0] = 1;
matrix[3][1] = 2;
matrix[3][2] = 3;
matrix[3][3] = 1;
But something goes wrong and my app dies at runtime=( What to do? How to embed values into vector of vectors correctly? 但出了点问题,我的应用程序在运行时死亡=(怎么做?如何正确地将值嵌入到向量的向量中?
Use this: 用这个:
std::vector< std::vector<int> > matrix(4, std::vector<int>(4));
This initializes your outer vector with 4 copies of std::vector<int>(4)
. 这将使用4个
std::vector<int>(4)
副本初始化外部向量。
In this case, you can take Björn's approach one step farther and fully initialize the 2D vector as you outlined with the values you supplied: 在这种情况下,您可以将Björn的方法更进一步,并使用您提供的值完全初始化2D矢量:
std::vector<int> tmp(4,0);
tmp[0] = 1;
tmp[1] = 2;
tmp[2] = 3;
tmp[3] = 1;
std::vector< std::vector<int> > matrix(4, tmp);
One could simply have written it as: 人们可以简单地把它写成:
std::vector<int> tmp(4,1);
tmp[1] = 2;
tmp[2] = 3;
std::vector< std::vector<int> > matrix(4, tmp);
but I often favor the first for clarity. 但为了清晰起见,我常常赞成第一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.