简体   繁体   English

用C ++初始化2d向量

[英]Initialzing a 2d vector in C++

I know that you can initialize a 1d vector with some value in the following way: 我知道您可以通过以下方式初始化具有某个值的1d向量:

vector<int> vec(10, 100); //creates a vector of size 10 and each element = 100

Now I would like to do the same thing with a 2d vector. 现在我想用2d矢量做同样的事情。 I know the following would give an error, because the size of columns is not specified: 我知道以下内容会产生错误,因为未指定列的大小:

vector<vector<int> > vec(10, 100);

So, is there any way to accomplish this? 那么,有什么方法可以实现这一目标吗? Also, I want to keep the column size same for each vector in the 2d vector (ie, an nxn grid). 此外,我想保持2d向量中每个向量的列大小相同(即nxn网格)。

Or maybe I can use the "std::fill()" function in some way to accomplish this? 或者也许我可以用某种方式使用“std :: fill()”函数来实现这个目的? And can this functionality be extended to an nxm grid? 这个功能可以扩展到nxm网格吗?

vector<vector<int>> vec(10, vector<int>(10, 100));
                //       n              m   value

This will create a vector of 10 vectors of size 10 and with elements initialized to 100. 这将创建10个大小为10的向量的向量,并将元素初始化为100。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM