Construct a vector of vectors in C++

This post provides an overview of the available alternatives to construct a vector of vectors in C++.


 

In C++, we can define a vector of vectors of ints as follows:

Above definition 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 resize() or push_back() functions, or using the fill constructor or initializer lists. Now let’s explore each alternative in detail:

 

1. resize() function

The resize() function is used to resize a vector to the specified size. We can use it to initialize a vector of vectors as shown below:

 

Download   Run Code

 
We can picture a vector of vectors as a two-dimensional array consisting of R rows and C columns. 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

 

2. push_back() function

Another plausible way of initializing a vector of vectors is to use the push_back() function which adds a given element at the end of the vector. Here’s a C++ program that demonstrates it:

 

Download   Run Code

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

 

3. Fill Constructor

The recommended approach is to use fill constructor of the vector container for constructing a vector of vectors. The fill constructor accepts an initial size n and a value and creates a vector of n elements and fills with the specified default value.

 

Download   Run Code

 
We can split above initialization into two parts – first initialize a vector of ints and then use this vector to initialize the vector of vectors using the fill constructor. This is demonstrated below:

 

Download   Run Code

 

4. Initializer list

Finally, we can use initializer lists introduced with C++11 to construct a vector of vectors as shown below:

 

Download   Run Code

 

How to print the vector of vectors?

The following procedure would display a vector of vectors of integer using nested loops:

 
1 Star2 Stars3 Stars4 Stars5 Stars (1 votes, average: 5.00 out of 5)

Loading...

Thanks for reading.

Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Categories

Leave a Reply

avatar
  Subscribe  
Notify of