Initialize a two-dimensional vector in C++

Google Translate Icon

This article will explore how to initialize a two-dimensional vector with a given default value in C++.

In C++, we can define a two-dimensional vector of ints as follows:

It results in an empty two-dimensional vector. To use it, we have to define the vector size and allocate storage for its elements. There are several methods to grow a two-dimensional vector with the help of the fill constructor, resize() or push_back() methods, or using initializer lists.

1. Using Fill Constructor

The recommended approach is to use a fill constructor to initialize a two-dimensional vector. The fill constructor creates a vector of the specified number of elements and fills with the specified value.

Download  Run Code

We can split the above initialization into two parts – first initialize a vector of ints with a given default value and then use it to initialize the two-dimensional vector. This is demonstrated below:

Download  Run Code

2. Using resize() function

The resize() function is used to resize a vector to the specified size. We can use it to initialize a two-dimensional vector with a given default value, as shown below:

Download  Run Code

Here’s an alternative version of the above code, which uses an overloaded version of the resize() function, which accepts the container size, and the object to be copied in that container.

Download  Run Code

3. Using push_back() function

Another plausible way of initializing a two-dimensional vector is to use the push_back() function, which adds the given element at the end of a vector. The following C++ program demonstrates it:

Download  Run Code

Note when dimensions M and N are large, the above code suffers from potential performance penalties caused by frequent reallocation of memory by the push_back() function. So, push_back() should be used only when vector dimensions are not known in advance.

4. Using Initializer Lists

Finally, we can use initializer lists to initialize a two-dimensional vector with a given default value, as shown below. Note this will only work with C++11 and above.

Download  Run Code

How to print the two-dimensional vector?

The following procedure would display a two-dimensional vector of integers using nested loops:

That’s all about initializing a two-dimensional vector in C++.

Rate this post

Average rating 4.55/5. Vote count: 58

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Tell us how we can improve this post?

Thanks for reading.

Please use our online compiler to post code in comments using C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.

Like us? Refer us to your friends and help us grow. Happy coding :)

Notify of
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Do NOT follow this link or you will be banned from the site!