cpp initialize multidimensional vector

#include <iostream>
#include <vector>

int main() {
    // Initialize a 2D vector with 3 rows and 4 columns
    std::vector<std::vector<int>> matrix(3, std::vector<int>(4));

    // Set values for each element in the matrix
    for (int i = 0; i < matrix.size(); i++) {
        for (int j = 0; j < matrix[i].size(); j++) {
            matrix[i][j] = i * j;
        }
    }

    // Print the matrix
    for (int i = 0; i < matrix.size(); i++) {
        for (int j = 0; j < matrix[i].size(); j++) {
            std::cout << matrix[i][j] << " ";
        }
        std::cout << std::endl;
    }

    return 0;
}
  1. Include the necessary headers:
  2. #include <iostream>: This header file provides basic input and output stream functionalities.
  3. #include <vector>: This header file provides the necessary functions and classes for working with vectors.

  4. Define the main() function, which is the entry point of the program.

  5. Initialize a 2D vector called matrix with 3 rows and 4 columns:

  6. std::vector<std::vector<int>> matrix: This declares a vector of vectors, where each element is an integer.
  7. (3, std::vector<int>(4)): This initializes the vector with 3 elements, each of which is a vector of size 4.

  8. Set values for each element in the matrix using nested loops:

  9. for (int i = 0; i < matrix.size(); i++): This iterates over each row of the matrix.
  10. for (int j = 0; j < matrix[i].size(); j++): This iterates over each column of the current row.
  11. matrix[i][j] = i * j;: This assigns the product of the row and column indices to the current element.

  12. Print the matrix using nested loops:

  13. for (int i = 0; i < matrix.size(); i++): This iterates over each row of the matrix.
  14. for (int j = 0; j < matrix[i].size(); j++): This iterates over each column of the current row.
  15. std::cout << matrix[i][j] << " ";: This prints the value of the current element followed by a space.
  16. std::cout << std::endl;: This prints a newline character to move to the next row.

  17. Return 0 to indicate successful program execution.