2d vector c++ declaration
To declare a 2D vector in C++, you can follow these steps:
Step 1: Include the necessary header file for using the vector class. In this case, you need to include the <vector>
header file.
Step 2: Declare a variable of type vector<vector<T>>
, where T
is the type of data you want to store in the 2D vector.
Step 3: Initialize the 2D vector by providing the dimensions and initial values (if any) using the constructor.
Here's an example of a 2D vector declaration in C++:
#include <vector>
int main() {
// Step 1: Include the necessary header file
// Step 2: Declare a variable of type vector<vector<T>>
std::vector<std::vector<int>> my2DVector;
// Step 3: Initialize the 2D vector with dimensions and initial values
int numRows = 3;
int numCols = 4;
int initialValue = 0;
my2DVector.assign(numRows, std::vector<int>(numCols, initialValue));
return 0;
}
In the above example, we have declared a 2D vector my2DVector
of type vector<vector<int>>
. We have initialized it with a size of 3 rows and 4 columns, with each element initialized to 0.
You can modify the type T
and the dimensions according to your requirements.