c++ initialize vector of vectors with 0 (zeros)

In this post, i will show you how to initialize c++ stl vector of vectors and fill them up with 0’s or zeros or in fact any other integer you prefer.

How to Initialize 2d vector

vector<vector<int>> table(rows, vector<int> (cols));

This in initialization will automatically fill the vector of vector with a default value of 0’s. rows is the count or size or rows and cols is the count or size of columns; meaning that if you wanted to create a 2d vector of 3 rows and 4 columns which is initialized to zeros, you should do this:

vector<vector<int>> table(3, vector<int> (4));

or if you like do this instead:

vector<vector<int>> table(3, vector<int> (4, 0));

The ouput is:

{
{0, 0, 0, 0},
{0, 0, 0, 0},
{0, 0, 0, 0}
}

how to fill 2d vector c++

But if you would like to fill the initial values of the 2d vector with some other values other than the default value of 0, you should do this instead:

vector<vector<int>> table(3, vector<int> (4, -1));

This code fills or initializes the 2d vector to -1. The output will be:

{
{-1, -1, -1, -1},
{-1, -1, -1, -1},
{-1, -1, -1, -1}
}
Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

You May Also Like