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:

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

1. Using 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 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

2. Using 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 vector’s end. The following C++ program demonstrates it:

Download  Run Code

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

3. Using Fill Constructor

The recommended approach uses a 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 the above initialization into two parts – first initialize a vector of ints and then use it to initialize the vector of vectors using the fill constructor. This is demonstrated below:

Download  Run Code

4. Using 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 an integer using nested loops:

That’s all about constructing a vector of vectors in C++.