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)字母数组。

示例

string letters[2][4] = {
  { "A", "B", "C", "D" },
  { "E", "F", "G", "H" }
};

cout << letters[0][2];  // Outputs "C"
亲自试一试 »

请记住:数组索引从 0 开始:[0] 是第一个元素。 [1] 是第二个元素,依此类推。


更改多维数组中的元素

要更改元素的值,请参考该元素在每个维度中的索引号:

示例

string letters[2][4] = {
  { "A", "B", "C", "D" },
  { "E", "F", "G", "H" }
};
letters[0][0] = "Z";

cout << letters[0][0];  // Now outputs "Z" instead of "A"
亲自试一试 »

循环遍历多维数组

要循环访问多维数组,需要对数组的每个维度进行一次循环。

以下示例输出中的所有元素字母数组:

示例

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";
  }
}
亲自试一试 »

此示例显示如何循环遍历三维数组:

示例

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";
    }
  }
}
亲自试一试 »

为什么是多维数组?

多维数组非常适合表示网格。这个例子展示了它们的实际用途。在下面的例子中我们使用一个多维数组来表示战舰小游戏:

示例

// 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";
运行示例 »