C++ 多维数组
多维数组
多维数组是数组的数组。
要声明多维数组,请定义变量类型,指定数组名称,后跟方括号(指定主数组有多少个元素),后跟另一组方括号(指示子数组有多少个元素)。
string letters[2][4];
与普通数组一样,可以在大括号内插入带有数组文字(逗号分隔的列表)的值。在多维数组中,数组文字中的每个元素都是另一个数组字面量。
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
数组声明中的每一组方括号都会为数组添加另一个维度。像上面这样的数组称为二维数组。
数组可以有任意数量的维度。数组的维数越多,代码就越复杂。下面的数组有三个维度:
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
访问多维数组的元素
要访问多维数组的元素,请在数组的每个维度中指定一个索引号。
此语句访问字母数组第一行(0)和第三列(2)中元素的值。
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
cout << letters[0][2];
return 0;
}
运行一下请记住:数组索引以 0 开头:[0] 是第一个元素。[1] 是第二个元素,等等。
更改多维数组中的元素
要更改元素的值,请引用每个维度中元素的索引
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
letters[0][0] = "Z";
cout << letters[0][0];
return 0;
}
运行一下
在多维数组中循环
要在多维数组中循环,数组的每个维度都需要一个循环。
以下实例输出字母数组中的所有元素:
#include <iostream>
using namespace std;
int main() {
string letters[2][4] = {
{ "A", "B", "C", "D" },
{ "E", "F", "G", "H" }
};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 4; j++) {
cout << letters[i][j] << "\n";
}
}
return 0;
}
运行一下这个例子展示了如何在三维数组中循环:
#include <iostream>
using namespace std;
int main() {
string letters[2][2][2] = {
{
{ "A", "B" },
{ "C", "D" }
},
{
{ "E", "F" },
{ "G", "H" }
}
};
for(int i = 0; i < 2; i++) {
for(int j = 0; j < 2; j++) {
for(int k = 0; k < 2; k++) {
cout << letters[i][j][k] << "\n";
}
}
}
return 0;
}
运行一下为什么是多维数组?
多维数组非常擅长表示网格。这个例子展示了它们的实际用途。在下面的实例中,我们使用多维数组来表示战舰的一个小游戏:
#include <iostream>
using namespace std;
int main() {
// We put "1" to indicate there is a ship.
bool ships[4][4] = {
{ 0, 1, 1, 0 },
{ 0, 0, 0, 0 },
{ 0, 0, 1, 0 },
{ 0, 0, 1, 0 }
};
// Keep track of how many hits the player has and how many turns they have played in these variables
int hits = 0;
int numberOfTurns = 0;
// Allow the player to keep going until they have hit all four ships
while (hits < 4) {
int row, column;
cout << "Selecting coordinates\n";
// Ask the player for a row
cout << "Choose a row number between 0 and 3: ";
cin >> row;
// Ask the player for a column
cout << "Choose a column number between 0 and 3: ";
cin >> column;
// Check if a ship exists in those coordinates
if (ships[row][column]) {
// If the player hit a ship, remove it by setting the value to zero.
ships[row][column] = 0;
// Increase the hit counter
hits++;
// Tell the player that they have hit a ship and how many ships are left
cout << "Hit! " << (4-hits) << " left.\n\n";
} else {
// Tell the player that they missed
cout << "Miss\n\n";
}
// Count how many turns the player has taken
numberOfTurns++;
}
cout << "Victory!\n";
cout << "You won in " << numberOfTurns << " turns";
return 0;
}
C 语言C++C#JavaPHPPYTHONGONode.jsPandasR 语言DjangoMatplotlibVB 教程ABAP 教程Fiori 教程汇编语言.NET Core 教程ASP.NET Core 教程Vue 教程Numpy机器学习SciPy分类导航