Learn 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;` // 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:

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

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, so once the above code gets executed it will have value of 3 (i.e. matrix = 3 ).

## 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).

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

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.

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.

 Published: November 24, 2022 Author: admin Category: Full Tutorials Views: 27