Initialize a two-dimensional vector in C++

In this article, we’ll explore how to initialize a two-dimensional vector with 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. In order to use it, we have to define 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. Fill Constructor

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

 

Download   Run Code

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

 

Download   Run Code

 

2. 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 given default value as shown below:

 

Download   Run Code

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

 

Download   Run Code

 

3. 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. Here’s a C++ program that demonstrates it:

 

Download   Run Code

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

 

4. C++11 – Initializer Lists

Finally, we can use initializer lists to initialize a two-dimensional vector with 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 intseger using nested loops:

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of