Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialzing a 2d vector in C++

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?

like image 281
Born Again Avatar asked Jan 26 '26 01:01

Born Again


1 Answers

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.

like image 117
jrok Avatar answered Jan 27 '26 14:01

jrok



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!