how to declare two d matrix in c++
#include <iostream>
#include <vector>
int main() {
int rows = 3; // Number of rows
int cols = 4; // Number of columns
std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));
return 0;
}
Explanation:
- #include <iostream>
: Includes the input/output stream library.
- #include <vector>
: Includes the vector library for using vectors in C++.
- int main() { ... }
: The main function where the program execution begins.
Within main()
:
- int rows = 3;
: Declares an integer variable rows
and assigns it the value 3, representing the number of rows in the matrix.
- int cols = 4;
: Declares an integer variable cols
and assigns it the value 4, representing the number of columns in the matrix.
- std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));
:
- Declares a 2D matrix named matrix
.
- std::vector<int>(cols)
creates a vector with cols
number of integers (representing a row).
- std::vector<std::vector<int>> matrix(rows, ...);
creates rows
number of such rows, forming a 2D matrix structure.
The resulting matrix will have 3 rows and 4 columns, initialized with default integer values (which are zeros for int
type).