c++ initialize vector of vector with size

#include <iostream>
#include <vector>

int main() {
    int rows = 3, cols = 4;

    std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));

    // Output the initialized matrix
    for (int i = 0; i < rows; ++i) {
        for (int j = 0; j < cols; ++j) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}

Explanation:

  • #include <iostream> and #include <vector>: These lines include necessary libraries for input/output operations and vectors respectively.

  • int rows = 3, cols = 4;: Declaration and initialization of variables rows and cols to store the number of rows and columns for the matrix.

  • std::vector<std::vector<int>> matrix(rows, std::vector<int>(cols));:

  • This line declares a 2D vector named matrix with the specified number of rows and columns.
  • std::vector<int>(cols) initializes each row with a vector of integers of size cols.
  • The outer vector's size is determined by the rows variable, and each row has cols number of elements.

  • Nested for loops:

  • for (int i = 0; i < rows; ++i) {: Loop iterating through each row.
  • for (int j = 0; j < cols; ++j) {: Loop iterating through each column within a row.
  • std::cout << matrix[i][j] << " ";: Outputs each element of the matrix separated by spaces.
  • std::cout << std::endl;: Outputs a newline to move to the next row in the console output.