Resizing a 2D vector

Resizing a 2D vector refers to changing its size dynamically, allowing you to add or remove rows and columns as needed. This can be useful when working with dynamic matrices or grids. In this blog post, we will explore how to resize a 2D vector in the C++ programming language.

Initializing a 2D Vector

Before we resize a 2D vector, we need to initialize it. To create a 2D vector in C++, consider the following code snippet:

#include <iostream>
#include <vector>

int main() {
    int rows = 3;
    int cols = 4;

    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols, 0));

    // Displaying the initial matrix
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << "\n";
    }

    return 0;
}

In this example, we create a 2D vector called matrix with 3 rows and 4 columns. The elements are initialized to 0. The initial matrix is then displayed using nested loops.

Resizing a 2D Vector

To resize a 2D vector, you can make use of the resize() function available in the C++ standard vector library. This function allows you to specify the new dimensions of the vector.

Let’s say we want to resize our matrix to have 5 rows and 6 columns. We simply call the resize() function as follows:

int newRows = 5;
int newCols = 6;
matrix.resize(newRows, std::vector<int>(newCols, 0));

This code resizes the matrix to have 5 rows and 6 columns with all elements initialized to 0.

Modifying the Size of a 2D Vector

Additionally, you can modify the size of the vector by adding or removing rows and columns. The resize() function can be used for this purpose as well.

To add a new row to the matrix, you can use the following code:

matrix.resize(matrix.size() + 1, std::vector<int>(newCols, 0));

This code adds a new row to the matrix with the specified number of columns.

To remove a row from the matrix, you can use the resize() function in combination with the pop_back() function:

matrix.resize(matrix.size() - 1);

This code removes the last row from the matrix.

Conclusion

Resizing a 2D vector in C++ allows for dynamic allocation and deallocation of memory, enabling flexible handling of matrices and grids. By using the resize() function, you can easily adjust the dimensions of the vector. Whether you want to initialize a 2D vector, resize it, or modify its size, the C++ standard vector library provides the necessary functionality.

#programming #cplusplus