create a 2d vector in c++
To create a 2D vector in C++, follow these steps:
- Include the necessary header file:
#include <vector>
- Declare the 2D vector variable:
std::vector<std::vector<int>> myVector;
- Initialize the size of the vector:
int rows = 3;
int columns = 4;
myVector.resize(rows, std::vector<int>(columns));
- Access and modify the elements of the vector:
myVector[0][0] = 1; // Assign a value to the element at row 0, column 0
int value = myVector[1][2]; // Retrieve the value of the element at row 1, column 2
- Iterate over the vector:
for (int i = 0; i < myVector.size(); i++) {
for (int j = 0; j < myVector[i].size(); j++) {
// Access and process each element of the vector
int element = myVector[i][j];
// ...
}
}
That's it! You now have a 2D vector in C++. Feel free to modify and use it as needed.