3

I know that you can initialize a 1d vector with some value in the following way:

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. 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 (i.e., an nxn grid).

Or maybe I can use the "std::fill()" function in some way to accomplish this? And can this functionality be extended to an nxm grid?

Born Again
  • 2,139
  • 4
  • 25
  • 27

1 Answers1

8
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.

jrok
  • 54,456
  • 9
  • 109
  • 141