In this article will discuss how to create 2D Matrix using vector of vectors in c++.

Requirement

Represent a 2D Matrix using vector in C++ i.e.

1 , 1 , 1 , 1
1 , 1 , 1 , 1
1 , 1 , 1 , 1
1 , 1 , 1 , 1
1 , 1 , 1 , 1

Declaration of 2D vector or vector of vector in C++

Initializing Vector of Vector – 2D vector

A vector can be initialized using parametrized constructor i.e.

std::vector <NUMBER OF ELEMENTS, VALUE OF EACH ELEMENT>

So,

Will create a vector of 4 integers whose values will be 1.

 

Now to create a vector of 5 vectors in which each vector is initialized as above, we will use following syntax,

Let’s see the code to initialize and print 2D vector as follows,

Output

1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,
1 , 1 , 1 , 1 ,

Iterator over 2D vector in C++

We can iterate over a vector of vector using [][] . Checkout the code below,

Adding a new row in 2D vector

To add a new row, just push_back a new vector in the vector of vector i.e.

Complete working Code is as follows,

Compile the above code using following command,

g++ –std=c++11 2dvector.cpp

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Do Subscribe with us for more Articles / Tutorials like this,