Code to find size of columns and rows in 2D vector in C++
#include <iostream>
#include <vector>
int main() {
std::vector<std::vector<int>> matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int rows = matrix.size();
int columns = matrix[0].size();
std::cout << "Number of rows: " << rows << std::endl;
std::cout << "Number of columns: " << columns << std::endl;
return 0;
}
Explanation
- Include the necessary headers for input-output stream and vectors.
- Define the main function.
- Create a 2D vector "matrix" and initialize it with some values.
- Get the number of rows in the matrix using
matrix.size()
. - Get the number of columns in the matrix by accessing the size of the first row
matrix[0].size()
. - Output the number of rows and columns to the console.