Latest web development tutorials

C ++ multidimensional arrays

C ++ Array C ++ Array

C ++ supports multidimensional arrays. The general form of a multidimensional array declaration is as follows:

type name[size1][size2]...[sizeN];

For example, the following statement creates a three-dimensional array of 5104 integers.:

int threedim[5][10][4];

Two-dimensional array

The simplest form of a multidimensional array is a two-dimensional array. A two-dimensional array, in essence, is a list of one-dimensional array. X row y column declared a two-dimensional array of integers in the form below:

type arrayName [ x ][ y ];

Wherein, type can be any valid C ++ data types,arrayName is a valid C ++ identifier.

A two-dimensional array can be considered a form x row and y column with. Here is a two-dimensional array containing 3 rows and 4:

Two-dimensional array in C ++

Thus, each element of the array is the use of the form a [i, j] element names to identify where a name is an array, i, and j is the unique identifier in a subscript of each element.

Two-dimensional array initialization

Multidimensional arrays can be initialized in parentheses to the specified value for each row. Here is an array of four rows with 3.

int a[3][4] = {  
 {0, 1, 2, 3} ,   /*  初始化索引号为 0 的行 */
 {4, 5, 6, 7} ,   /*  初始化索引号为 1 的行 */
 {8, 9, 10, 11}   /*  初始化索引号为 2 的行 */
};

Inside nested parentheses are optional, the following initialization is equivalent to the above:

int a[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Two-dimensional array element access

Two-dimensional array element by using the subscript (ie, the array row index and column index) to visit. E.g:

int val = a[2][3];

The above statement will get the first four elements in the array on line 3. You can be verified by the above diagram. Let's look at the following program, we will use a nested loop to process two-dimensional array:

#include <iostream>
using namespace std;
 
int main ()
{
   // 一个带有 5 行 2 列的数组
   int a[5][2] = { {0,0}, {1,2}, {2,4}, {3,6},{4,8}};
 
   // 输出数组中每个元素的值                      
   for ( int i = 0; i < 5; i++ )
      for ( int j = 0; j < 2; j++ )
      {
         cout << "a[" << i << "][" << j << "]: ";
         cout << a[i][j]<< endl;
      }
 
   return 0;
}

When the above code is compiled and executed, it produces the following results:

a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8

As described above, you can create arrays of any dimension, but under normal circumstances, we have created an array of one-dimensional arrays and two-dimensional array.

C ++ Array C ++ Array