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;
}
- Include the necessary headers:
#include <iostream>
: This header file provides basic input and output stream functionalities.#include <vector>
: This header file provides the necessary functions and classes for working with vectors.Define the
main()
function, which is the entry point of the program.Initialize a 2D vector called
matrix
with 3 rows and 4 columns:std::vector<std::vector<int>> matrix
: This declares a vector of vectors, where each element is an integer.(3, std::vector<int>(4))
: This initializes the vector with 3 elements, each of which is a vector of size 4.Set values for each element in the matrix using nested loops:
for (int i = 0; i < matrix.size(); i++)
: This iterates over each row of the matrix.for (int j = 0; j < matrix[i].size(); j++)
: This iterates over each column of the current row.matrix[i][j] = i * j;
: This assigns the product of the row and column indices to the current element.Print the matrix using nested loops:
for (int i = 0; i < matrix.size(); i++)
: This iterates over each row of the matrix.for (int j = 0; j < matrix[i].size(); j++)
: This iterates over each column of the current row.std::cout << matrix[i][j] << " ";
: This prints the value of the current element followed by a space.std::cout << std::endl;
: This prints a newline character to move to the next row.Return 0 to indicate successful program execution.