## How to initialize 2d vector in c++?

A vector can also be declared with data type as the vector itself. This is called a vector of vector or **2d vector**.

For example, take any grid with more than one row and more than one column. **2d vectors** form the basis of creating matrices, tables, or any data structures with dynamic properties in c++. Now we will look at 2d vector initialization in C++. If you encounter any problem with linear vector initialization, then refer __here__.

Before 2d vector initialization in c++, we need to introduce a new header file **#include<vector>**. It contains all the operations made or performed by any vector. The basic syntax for declaring any empty vector is as follows:

### C++

`#include <bits/stdc++.h>`

#include <vector>

using namespace std;

int main()

{

vector<int> v; // empty vector of size 0

v.push_back(10); // size 1

v.push_back(20); // size 2

vector<vector<int>> v2d; // empty 2d vector of size 0

v2d.push_back(v); // size 1

// currently the size of v2d is 1 because we pushed

// one vector v in it

v.push_back(30); // size 3

v2d.push_back(v); // size 2

}

For simplicity, we can think of a 2d vector as a vector's vector, i.e., if we access **v2d[i]**, it can be treated as a separate vector. Also, **v2d** can be treated as a vector itself, with its data type being a vector.

Let us look at some of the ways for 2d vector initialization in C++ at the time of declaration:

### 2D vector initialization in c++ with predefined values

We will look for some methods of 2d vector initialization in c++ where we are already given the values for each cell with its position in the 2d vector.

**Method 1**

```
#include <bits/stdc++.h>
using namespace std;
int main()
{
vector<vector<int>> v2d{
{1,2,3},
{4,5,6},
{7,8,9}};
// Here, v2d is a 2D vector with three rows and three columns
// its values are already initialized
}
```

Now we will look for a method of 2d vector initialization in c++ having different sizes of different rows with predefined values.

```
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<vector<int>> v2d{
{1, 2, 3},
{4, 5},
{6, 7, 8, 9}
};
// Here, v2d is a 2D vector with three rows
// 1st row has 3 elements
// 2nd row has 2 elements
// 3rd row has 4 elements
// its values are already initialized
}
```

**Method 2**

Now let’s look at another method of 2d vector initialization in c++ where we have been given the number of columns for different rows., i.e., we will be provided with an array having the number of columns for the given row.

### C++

`#include <bits/stdc++.h>`

using namespace std;

int main() {

vector < int > col = {1,3,6,2,3};

vector < vector < int >> v2d(5); // v2d initialized with 5 rows

for (int i = 0; i < col.size(); i++) {

v2d[i].resize(col[i]); // each row resized to col[i] columns

for (int j = 0; j < col[i]; j++) {

v2d[i][j] = i * j; //we assigned values to each element

}

}

for (int i = 0; i < v2d.size(); i++) {

for (int j = 0; j < v2d[i].size(); j++) {

cout << v2d[i][j] << " ";

}

cout << "\n";

}

}

**Output:**

```
0
0 1 2
0 2 4 6 8 10
0 3
0 4 8
```

You can practice by yourself with the help of __Online C++ Compiler__ for better understanding.

The resize() function basically increases or decreases the size of the vector without affecting the previous values in the vector. For more information, refer to the bottom of the blog.

Here we knew the number of rows, and for which row how many columns are required. So,

- we initialized the 2d vector with the number of rows.
- Now iterating through each row, we assigned the number of columns to the respective rows as mentioned in the array.
- Then iterating through each cell, we assigned them a new value
* (we can also take ***std::cin** here).

### 2D vector initialization in c++ with predefined size

Now we will declare the 2d vector with all of its cells filled with the same values and having a predefined number of rows and columns.

**Method 1**

```
#include <bits/stdc++.h>
using namespace std;
int main(){
vector<vector<int>> v2d(3, vector<int>(3, 0));
// this is a 3x3 matrix with all elements 0
}
```

Its time and space complexity will be **O(N*N),** with **N** being its number of rows and columns. It is the same as declaring a vector of vectors of size three and then, for each such vector declaring them with size three and value 0.

There is also a way for 2d vector initialization in c++ with the given size and values for each cell and having a predefined number of rows and columns. Implementation of the same is as follows

**Method 2**

### C++

`#include <bits/stdc++.h>`

using namespace std;

int main(){

int row = 4;

int col = 3;

vector<vector<int>> v2d(row, vector<int>(col));

// declare a 2d vector of size row*col

for(int i=0;i<row;i++){

for(int j=0;j<col;j++){

v2d[i][j] = i*col + j;

}

}

// here, we have filled the 2d vector with values

}

Using this method, we can fill the values in each cell according to our needs, we can also use *std::cin* here.

### Re-initializing the 2D vector

**Method 1**

We can also re-initialize an already declared and initialized 2d vector in c++. For this, we use the **assign()** function.

### C++

`#include <bits/stdc++.h>`

using namespace std;

int main(){

int row = 4;

int col = 3;

vector<vector<int>> v2d(row, vector<int>(col, 0));

// declare a 2d vector of size row*col and initialize all elements to 0.

int new_row = 5;

int new_col = 4;

v2d.assign(new_row, vector<int>(new_col, -1));

// resized the 2d vector to new_row*new_col and initialized all elements to -1.

}

Here we first declared and initialized the **v2d** vector of **row*col** with the value of each cell as 0. Then, with the **assign()** function, we reassigned the **v2d** vector with new properties of **size new_row*new_col** with the value of each cell as -1.

**Method 2**

Now we will look at a method to resize the already-defined vector and then assign values to the new cells.

Resize () function in c++ means holding old data and expanding the new vector with new elements in case the new size is greater than the old one. Otherwise, shrink the size and eliminate the extra.

### C++

`#include <bits/stdc++.h>`

using namespace std;

int main(){

int row = 4;

int col = 3;

vector<vector<int>> v2d(row, vector<int>(col, 0));

// declare a 2d vector of size row*col and initialize all elements to 0.

int new_row = 6;

int new_col = 4;

v2d.resize(new_row, vector<int>(new_col, -1));

// resized the 2d vector to new_row*new_col and initialized all new elements to -1.

for(int i=0;i<v2d.size();i++){

for(int j=0;j<v2d[i].size();j++){

cout<<v2d[i][j]<<" ";

}

cout<<endl;

}

}

**Output:**

```
0 0 0
0 0 0
0 0 0
0 0 0
-1 -1 -1 -1
-1 -1 -1 -1
```

As you can see in the output, the new rows and columns are added with new properties and values of new cells as -1.

Also check out this article - __Pair in C++__

**Specifying the Size for 2D Vector Initialization**

To specify the size of a 2D vector during initialization, you can define the number of rows and columns and initialize them with a default value. This is done using the constructor of the **vector** class.

### C++

`#include <iostream>`

#include <vector>

int main() {

int rows = 3;

int cols = 4;

int defaultValue = 0;

// Initialize a 2D vector with 3 rows and 4 columns, all elements set to 0

std::vector<std::vector<int>> vec(rows, std::vector<int>(cols, defaultValue));

// Print the 2D vector

for (int i = 0; i < rows; ++i) {

for (int j = 0; j < cols; ++j) {

std::cout << vec[i][j] << " ";

}

std::cout << std::endl;

}

return 0;

}

**Output:**

```
0 0 0 0
0 0 0 0
0 0 0 0
```

**Iterators for 2D Vectors**

Iterators are used to traverse the elements of a 2D vector. Nested loops with iterators can be employed to access and manipulate elements.

### C++

`#include <iostream>`

#include <vector>

int main() {

std::vector<std::vector<int>> vec = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};

// Iterate through the 2D vector using iterators

for (auto row = vec.begin(); row != vec.end(); ++row) {

for (auto col = row->begin(); col != row->end(); ++col) {

std::cout << *col << " ";

}

std::cout << std::endl;

}

return 0;

}

**Output:**

```
1 2 3
4 5 6
7 8 9
```

**Add Elements to a 2-D Vector**

To add elements to a 2D vector, you can use the **push_back** method. This allows you to append new rows or add elements to existing rows.

### C++

`#include <iostream>`

#include <vector>

int main() {

std::vector<std::vector<int>> vec;

// Adding new rows to the 2D vector

vec.push_back({1, 2, 3});

vec.push_back({4, 5, 6});

vec.push_back({7, 8, 9});

// Adding an element to an existing row

vec[0].push_back(10);

// Print the 2D vector

for (const auto& row : vec) {

for (int elem : row) {

std::cout << elem << " ";

}

std::cout << std::endl;

}

return 0;

}

**Output:**

```
1 2 3 10
4 5 6
7 8 9
```

**Remove Elements from a 2-D Vector**

To remove elements from a 2D vector, you can use the **pop_back** method to remove the last element of a row or the last row of the vector. You can also use the **erase** method for more specific deletions.

### C++

`#include <iostream>`

#include <vector>

int main() {

std::vector<std::vector<int>> vec = {{1, 2, 3, 10}, {4, 5, 6}, {7, 8, 9}};

// Remove the last element from the first row

vec[0].pop_back();

// Remove the last row

vec.pop_back();

// Print the 2D vector

for (const auto& row : vec) {

for (int elem : row) {

std::cout << elem << " ";

}

std::cout << std::endl;

}

return 0;

}

**Output:**

```
1 2 3
4 5 6
```

## Frequently Asked Questions

**What is a 2d vector?**

It can be referred to as a vector of vectors or a 2d grid with dynamic properties. Here by dynamic properties, we mean that we can resize the 2d vector according to our need in between the code and assign values according to our requirements.

**How to initialize a vector of size N*M and all values with ‘val’ (type=char)?**

We can use many methods, as discussed above. Let’s look at the syntax of one of the method

`vector<vector<char>> v2d(n, vector<char>(m, val));`

**What are the time and space complexities of declaring and initializing any 2d vector?**

If we are declaring a vector and not assigning rows and columns to it, then its time and space complexity is O(1), i.e., constant. But if we are initializing a 2d vector with n rows and m columns, its space and time complexity will be O(N*M).

**How to push in 2D vector in C++?**

To push elements into a 2D vector in C++, use the **push_back** method. You can add new rows with **vec.push_back({elements})** and append elements to an existing row with **vec[row].push_back(element)**.

**How to declare a 2D vector in C++ with given size?**

To declare a 2D vector with a given size in C++, use **vector<vector<T>> vec(rows, vector<T>(cols, defaultValue));**, where **rows** and **cols** specify the dimensions, and **defaultValue** initializes all elements.

## Conclusion

This article discussed 2d vector initialization in c++ techniques for different cases in __C++__. We also discussed how we could reinitialize or resize any already existing 2d vector. At last, we explored the time and space complexity of declaring and initializing any 2d vector.

If you found this blog interesting, you can refer to some of the blogs mentioned below

Visit our website to read more such blogs. Make sure you enroll in the __courses__ we provide, take __mock test__s, solve __problems__, and __interview puzzles__. Also, you can pay attention to interview stuff- __interview experiences__ and __an interview bundle__ for placement preparations.