Codementor Events

2D Matrix vs 2D Vector

Published Nov 19, 2022
2D Matrix vs 2D Vector

INTRODUCTION

2D matrix also known as array of arrays has their size allocated in the beginning, hence are static mode of row-column representation.
2D vector also knows as vector of vectors are dynamic growing arrays in which user does not define initial size of how many rows and columns would exist, are dynamic mode of row-column representation.

CREATION AND INSERTION INTO 2D MATRIX

int matrix[3][4]; // Size has been allocated in the beginning.
Here number of rows = 3, and no of columns = 4.

To populate each row and column we write code as:

for (int i = 0; i < 3; i++) // This loop is run for each row.
{
  for(int j = 0; j < 4; j++) // This loop is run for each column
    {
    	matrix[i][j] = i+j; // We are inserting (value = i+j) into i-th row & j-th column.
    }
}

We will be traversing 0th row, 1st row, 2nd row (0-based indexing) and 0th, 1st, 2nd, 3rd column respectively for each row.
Suppose we are in 1st row - 2nd column means matrix[1][2], so once the above code gets executed it will have value of 3 (i.e. matrix[1][2] = 3 ).
1.jpg
2.jpg

CREATION AND INSERTION IN 2D VECTORS

vector < vector <int> > vec; // Initializing the vector of vectors
Here we have defined that there will be vector of vectors ( 1 vector in itself is dynamic array, so vector of vectors means list of dynamically growing arrays).

    vector<vector<int> > vec;
    int rows = 3;
    for (int i = 0; i < rows; i++) {
        vector<int> v1;     // Vector to store column elements
        int columns = i+2;  // We are adding i+2 columns in each row, hence dynamic.
        for (int j = 0; j < columns; j++) {
            v1.push_back(20);
        }
        vec.push_back(v1);  // Pushing back above 1D vector to create the 2D vector.
    }

For the above code the outer loop runs for 3 times i.e 3 rows.
But inner loop runs i+2 times meaning for
row = 0 , columns = 0+2 = 2 (0th row has 2 columns)
row = 1 , columns = 1+2 = 3 (1st row has 3 columns)
row = 2 , columns = 2+2 = 4 (2nd row has 4 columns)
Just for understanding purpose we are inserting value = 20 at each position.
3.jpg

Main advantage of 2d vectors lies in the fact that you are only assigning the memory according to your requirement, and are not bound to allocate fixed spaces even if they are not required unlike 2d arrays which have there size initialized in the beginning.

In the above examples you now have the idea that 2d arrays means no. of columns are fixed for each row which is not with the 2d vectors.

Discover and read more posts from RAMANDEEP SINGH
get started
post comments9Replies
Alok Hirekhan
2 years ago

Simple & nice article… looking forward to see more from you Ramandeep :)

Shakil-Hassan
2 years ago

Awesome Simplification.

Simranjeet Singh
2 years ago

Simplified version of 2d array vs 2d vector…Great mentor!!

Show more replies