C++ 2D Vector with Examples – Vector of Vectors

It is a vector consisting of vectors. As the name suggests it is 2-Dimensional in nature and can help you solve problems. In this tutorial, you will learn how to work with 2d vectors in C++.

How to Take Input in 2D Vector?

Output:

Enter the number of vectors you have 2
Enter the number of elements you have in this vector 2
Enter the data of this item 2
Enter the data of this item 3
Enter the number of elements you have in this vector 2
Enter the data of this item 3
Enter the data of this item 4

Code Explanation:

First of all, we include all the important libraries including the vector library. Now we declare the 2D vector by vector<vector<int>> allvect. allvect is going to contain all the vectors as its elements.

Now we take the input that how many vector elements are there in the count variable.

After this, we run a for loop for taking input of all the elements of each vector. Then we use push_back function to add elements in allvect. 

Tip: You can use 2D vectors in all the cases of 2D array whereas vice versa is not possible.

How to Initialize 2D Vector?

How to Print 2D Vector?

Output:

1 2 3
4 5 6
7 8
9 10 11 12

How to Iterate Through 2D Vector Using Iterators?

How to Iterate Through 2D Vector Through Indexing?

So these were some characteristics of a 2D vector in c++. Feel free to comment below if you have more doubts regarding it.

Leave a Comment

Your email address will not be published.