Creating a 2D vector in C++

In this blog post, we will explore how to create a 2D vector in C++. Vectors are an essential data structure that allows us to dynamically store and manipulate collections of elements.

What is a 2D Vector?

A 2D vector, also known as a matrix, is a collection of elements arranged in rows and columns. It can be visualized as a table or grid, where each element is accessed using its row and column index.

Initializing a 2D Vector

To create a 2D vector in C++, you need to include the <vector> header file.

#include <vector>

You can initialize a 2D vector by specifying its size and initial value. For example, to create a 3x3 matrix with all elements initialized to 0, you can use the following code:

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

In the above code, std::vector<std::vector<int>> represents the data type of the 2D vector. matrix is the name of the 2D vector, and (3, std::vector<int>(3, 0)) is the size and initial value of each element.

Accessing Elements in a 2D Vector

You can access elements in a 2D vector by specifying their row and column indices. For example, to access the element at row i and column j of the matrix, you can use the following code:

matrix[i][j]

Modifying Elements in a 2D Vector

You can modify elements in a 2D vector in a similar way to accessing them. For example, to change the value of the element at row i and column j of the matrix to newValue, you can use the following code:

matrix[i][j] = newValue;

Conclusion

In this blog post, we have learned how to create and manipulate a 2D vector in C++. Vectors are a powerful data structure that can be used in various applications, such as matrix operations, image processing, and graph algorithms.