## Introduction

A vector is a dynamic array that is built into a standard ** C++** library. This vector class can grow in size dynamically. The elements are arranged in a continuous manner so that iterators can traverse them. To learn more about vectors, you can visit

__here__.

In this article, we will see an introduction to vectors, 2D vectors, vector of vectors in c++, examples of vectors, and implementation in detail.

## 2D vectors

A vector of the vector is a 2D vector. A 2D vector is like a 2D array which can be declared and assigned values.

Now, let’s understand the 2d vectors with the help of an implementation.

### Implementation 1

```
/* Program to demonstrate a 2D vector where
each of its elements is of a different size.*/
#include <iostream>
#include <vector>
using namespace std;
int main()
{
/*
We initialize a 2D vector
named "vect" on line 16 with
different number of values
in each element.
*/
vector<vector<int>> vec{
/* Element one with two values in it. */
{'a', 'b'},
/* Element two with three values in it. */
{'c', 'd', 'e'},
/* Element three with four values in it. */
{'f', 'g', 'h', 'i'}};
/*
Now we will print the vector that we
just defined using the simple
nested for loops.
*/
for (int m = 0; m < vec.size(); m++)
{
for (int k = 0; k < vec[m].size(); k++)
{
char c = (char)vec[m][k];
cout << c << " ";
}
cout << "\n";
}
return 0;
}
```

**Output**

**Time complexity**

O(N*N) since N is the size of the vector.

**Space complexity**

O(N) as N is the size of the vector.

2D vectors are commonly depicted as a matrix with "rows" and "columns". They are 2D vector elements under the hood.

We then establish an integer variable called "row," followed by an array called "column," which will hold the size of the row. We will then proceed to initialize the memory of each row by the column size.

### Implementation 2

```
// Program to insert into a vector of vectors in c++
// CPP program
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int row;
int col;
cout << "Enter the number of row and column respectively\n";
cin >> row >> col;
/*
Create a vector containing "n"
vectors each of size "m".
*/
cout << "2D vector Matrix after inserting the values\n";
vector<vector<int>> vect(row, vector<int>(col));
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
vect[i][j] = j + i + 1;
}
}
for (int i = 0; i < row; i++)
{
for (int j = 0; j < col; j++)
{
cout << vect[i][j] << " ";
}
cout << endl;
}
return 0;
}
```

**Output**

**Time complexity**

O(row*col) as we have used a nested loop to build and print a matrix.

**Space complexity**

The space complexity is O(N), where N is the size of the vector.

Read More - __Time Complexity of Sorting Algorithms__