📜  C++多维数组

📅  最后修改于: 2020-09-25 05:00:14             🧑  作者: Mango

###### 在本教程中，我们将学习C++中的多维数组。更具体地说，如何在我们的程序中声明，访问它们以及有效地使用它们。

``int x[3][4];``

``float x[2][4][3];``

``2 x 4 x 3 = 24``

### 1.二维数组的初始化

``int test[2][3] = {2, 4, 5, 9, 0, 19};``

``int  test[2][3] = { {2, 4, 5}, {9, 0, 19}};``

### 2.三维数组的初始化

``````int test[2][3][4] = {3, 4, 2, 3, 0, -3, 9, 11, 23, 12, 23,
2, 13, 4, 56, 3, 5, 9, 3, 5, 5, 1, 4, 9};``````

``````int test[2][3][4] = {
{ {3, 4, 2, 3}, {0, -3, 9, 11}, {23, 12, 23, 2} },
{ {13, 4, 56, 3}, {5, 9, 3, 5}, {5, 1, 4, 9} }
};``````

#### 示例1：二维数组

``````// C++ Program to display all elements
// of an initialised two dimensional array

#include
using namespace std;

int main() {
int test[3][2] = {{2, -5},
{4, 0},
{9, 1}};

// use of nested for loop
// access rows of the array
for (int i = 0; i < 3; ++i) {

// access columns of the array
for (int j = 0; j < 2; ++j) {
cout << "test[" << i << "][" << j << "] = " << test[i][j] << endl;
}
}

return 0;
}``````

``````test[0][0] = 2
test[0][1] = -5
test[1][0] = 4
test[1][1] = 0
test[2][0] = 9
test[2][1] = 1``````

#### 示例2：获取二维数组的输入

``````#include
using namespace std;

int main() {
int numbers[2][3];

cout << "Enter 6 numbers: " << endl;

// Storing user input in the array
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cin >> numbers[i][j];
}
}

cout << "The numbers are: " << endl;

//  Printing array elements
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
cout << "numbers[" << i << "][" << j << "]: " << numbers[i][j] << endl;
}
}

return 0;
}``````

``````Enter 6 numbers:
1
2
3
4
5
6
The numbers are:
numbers[0][0]: 1
numbers[0][1]: 2
numbers[0][2]: 3
numbers[1][0]: 4
numbers[1][1]: 5
numbers[1][2]: 6``````

#### 示例3：三维数组

``````// C++ Program to Store value entered by user in
// three dimensional array and display it.

#include
using namespace std;

int main() {
// This array can store upto 12 elements (2x3x2)
int test[2][3][2] = {
{
{1, 2},
{3, 4},
{5, 6}
},
{
{7, 8},
{9, 10},
{11, 12}
}
};

// Displaying the values with proper index.
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 2; ++k) {
cout << "test[" << i << "][" << j << "][" << k << "] = " << test[i][j][k] << endl;
}
}
}

return 0;
}``````

``````test[0][0][0] = 1
test[0][0][1] = 2
test[0][1][0] = 3
test[0][1][1] = 4
test[0][2][0] = 5
test[0][2][1] = 6
test[1][0][0] = 7
test[1][0][1] = 8
test[1][1][0] = 9
test[1][1][1] = 10
test[1][2][0] = 11
test[1][2][1] = 12``````

3d阵列的打印元素的基本概念类似于2d阵列的打印概念。