# 如何在 C++ 中使用 new 声明 2D 数组

## 用 `arr[x][y]` 记法声明二维数组来访问元素

``````#include <iostream>
#include <iomanip>

using std::cout; using std::cin;
using std::endl; using std::setw;

constexpr int ROW = 4;
constexpr int COL = 6;

int main()
{
int **matrix = new int*[ROW];
for(int i = 0; i < ROW; ++i) {
matrix[i] = new int[COL];
}

for(int i = 0; i < ROW; ++i) {
for(int j = 0; j < COL; ++j) {
matrix[i][j] = rand() % 100;
cout << setw(2) << matrix[i][j] << "; ";
}
cout << endl;
}

for(int i = 0; i < ROW; ++i) {
delete matrix[i];
}
delete [] matrix;
return EXIT_SUCCESS;
}
``````

``````83; 86; 77; 15; 93; 35;
86; 92; 49; 21; 62; 27;
90; 59; 63; 26; 40; 26;
72; 36; 11; 68; 67; 29;
``````

## 用 `arr[]` 记法声明 2D 数组来访问元素

``````#include <iostream>
#include <iomanip>

using std::cout; using std::cin;
using std::endl; using std::setw;

constexpr int ROW = 4;
constexpr int COL = 6;

int main()
{
int *matrix = new int[ROW * COL];

for(int i = 0; i < ROW; ++i) {
for(int j = 0; j < COL; ++j) {
matrix[j * ROW + i] = rand() % 100;
cout << setw(2) << matrix[j * ROW + i] << "; ";
}
cout << endl;
}
delete [] matrix;

return EXIT_SUCCESS;
}
``````

## 使用 `vector` 容器隐式分配动态二维数组

``````#include <iostream>
#include <vector>
#include <iomanip>

using std::cout; using std::vector;
using std::endl; using std::setw;

constexpr int ROW = 4;
constexpr int COL = 6;

int main()
{
vector<vector<int> > vector_2d(ROW, vector<int> (COL, 0));

for (auto &item : vector_2d) {
for (auto &item1 : item) {
item1 = rand() % 100;
cout << setw(2) << item1 << "; ";
}
cout << endl;
}
return EXIT_SUCCESS;
}
``````