在C++中,可以使用指针数组或vector容器来实现动态二维数组,并对其进行初始化。以下是两种方法:
使用指针数组:int rows = 3;int cols = 4;// 初始化动态二维数组int **arr = new int*[rows];for (int i = 0; i < rows; i++) { arr[i] = new int[cols];}// 对数组进行赋值for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { arr[i][j] = i * cols + j; }}// 释放内存for (int i = 0; i < rows; i++) { delete[] arr[i];}delete[] arr;使用vector容器:int rows = 3;int cols = 4;// 初始化动态二维数组std::vector<std::vector<int>> arr(rows, std::vector<int>(cols));// 对数组进行赋值for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { arr[i][j] = i * cols + j; }}以上两种方法都可以实现动态二维数组的初始化和赋值操作,选择哪种方法取决于具体的需求和使用场景。


