SoFunction
Updated on 2025-04-08

C++ Primer Multidimensional Array Use

Multidimensional array

Strictly speaking, C++ language does not have multi-dimensional arrays, and the commonly referred to as multi-dimensional arrays are actually arrays of arrays. Keeping this in mind will be of great benefit to understanding and using multidimensional arrays in the future.

When an array's elements are still arrays, two dimensions are usually used to define it: one dimension represents the size of the array itself, and the other dimension represents its element (also an array) size:

int ia[3][4];//Arrays of size 3, each element is an array containing 4 integers//Arrays of size 10, each element of it is an array of size 20,//The elements of these arrays are arrays containing 30 integersint arr[10][20][30]={0};//Initialize all elements to 0

Reading such definitions in an inside out order helps to better understand their true meaning. In the first statement, the name we define is ia, which is obviously an array with 3 elements. Then I observed the right and found that the elements of ia also have their own dimensions, so the elements of ia themselves are arrays containing 4 elements. Looking at the left, you will know that the real stored element is an integer. Therefore, the meaning of the first statement can be clarified in the end: it defines an array of size 3, and each element of the array is an array containing 4 integers.

Use the same method to understand the definition of arr. First of all, arr is an array of size 10. Each element of it is an array of size 20. The elements of these arrays are arrays containing 30 integers. In fact, there is no limit on the number of subscript operators when defining an array, so as long as Ciyi, you can define an array: its elements are still arrays, the elements of the next-level array are arrays, and so on.

For two-dimensional arrays, the first dimension is often called a row and the second dimension is called a column.

Initialization of multidimensional arrays

It is allowed to initialize multi-dimensional arrays with a set of values ​​enclosed in curly braces, which is the same as ordinary arrays. In the following initialization form, each line of the multi-dimensional array is enclosed in curly braces:

int ia[3][4] = { // Three arrays, each element is an array of size 4{0,1,2,3},       // The initial value of the first line{4,5,6,7},       // The initial value of the second line{8,9,10,11}      // The initial value of the third line}

The curly braces wrapped in the inner layer are not necessary. For example, the following initialization statement is more concise in form, and the completed function is exactly the same as the above code:

//There is no curly braces that identifies each line, which is equivalent to the previous initialization statementint ia[3][4] = {0,1,2,3,4,5,6,7,8,9,10,11};

Similar to a one-dimensional array, not all elements' values ​​must be included in the initialization list when initializing a multidimensional array. If you just want to initialize the first element of each line, you can use the following statement:

//Explanatory initialization of the first element of each lineint ta[3][4] = {{0},{4},{8}};

Other unlisted elements perform default initialization, and this process is the same as a one-dimensional array. In this case, if the inner braces are omitted, the result will be very different. The following code

//Explanatory initialization of line 1, other elements perform value initializationint ix[3][4]={0,3,6,9};

The meaning has changed. It initializes 4 elements in the first row, and other elements are initialized to 0.

Subscript reference for multi-dimensional arrays

You can use the subscript operator to access the elements of a multi-dimensional array. At this time, each dimension of the array corresponds to a subscript operator.

If the expression contains as many subscript operators as the array's dimensions, the result of the expression will be elements of the given type; conversely, if the expression contains less number of subscript operators than the array's dimensions, the result of the expression will be an inner-layer array at the given index:

// Use the first element of arr to assign the last element of the last line of iaia[2][3]=arr[0][0][0];
int(&row)[4]=ia[1];//Bind row to the second 4-element array of ia

In the first example, for the two arrays used, the number of subscript operators provided by the expression is the same as their respective dimensions. On the left side of the equal sign, ia[2] gets the last row of the array ia. At this time, the one-dimensional array representing the last row of ia is returned instead of any actual element; take the subscript for this one-dimensional array and get the element numbered [31, which is the last element of this row.
Similarly, the operation object on the right side of the equal sign contains 3 dimensions. First, we obtain the outermost array by indexing 0, which is a (multi-dimensional) array of size 20; then we obtain the first element of these 20 element arrays to obtain a one-dimensional array of size 30; finally we take out the first element of it.

In the second example, define row as a reference to an array of 4 integers, and bind it to line 2 of ia.

To give another example, two-layer nested for loops are often used in programs to process elements of multi-dimensional arrays:

constexpr size_t rowCnt=3,colCnttwo4;
intia[rowCnt][colCnt];//12 uninitialized elements//For each linefor(size_t i = 0;i!=rowCnt;++i) {
    //For each column in the row    for(stze_t j=0;j!=colCnt;++j) {
    //Index the position of the element as its value        ia[i][j]= i *colCnt + j;
    }
}

The outer for loop traverses all elements of ia, note that the elements here are one-dimensional arrays; the inner for loop traverses the integer elements of those one-dimensional arrays. In this example, we set the value of the element to the order number of the element in the entire array.

Use range for statement to handle multidimensional arrays

Since a scope for statement is added to the new C++11 standard, the previous program can be simplified to the following form:

size_t cnt = 0;

for(auto& row:ia)  //For each element of the outer array    for(auto&col:row){//For each element of the inner layer array        col=cnt;// Assign the next value to the element        ++cnt;//Add cnt 1}

The value assigned to the ia element by this loop is exactly the same as the previous loop. The difference is that the task of managing array indexes is handed over to the system by using the scope for statement. Because the value of the element is to be changed, the control variable row and col must be declared as reference types. The first for loop traverses all elements of ia. These elements are arrays of size 4, so the type of row should be a reference to an array containing 4 integers. The second for loop traverses one of those 4-element arrays, so the type of col is a reference to an integer. Each iteration assigns the value of cnt to the current element of ia, and then adds cnt to 1.

In the above example, because we want to change the value of the array element, we choose the reference type as the loop control variable, but in fact there is a deeper reason that prompts us to do so. For example, consider the following loop:

for(const auto&row:ia)   // For each element of the outer array    for(auto col:row)    // For each element of the inner layer array        cout<<col<<endl;

There is no write operation in this loop, but we still declare the control variables of the outer loop as reference type, which is to avoid the array being automatically converted into pointers. Assuming that reference types are not used, the loop is as follows:

for(auto row : ia)
    for(auto col:row)

The program will not be compiled. This is because, like before, the first loop goes through all elements of ia, note that these elements are actually arrays of size 4. Because row is not a reference type, the compiler will automatically convert these array-form elements (like other arrays) into pointers to the first element in the array when initializing col. The type of row obtained in this way is int*. Obviously, the inner loop is illegal. The compiler will try to traverse within an int*, which is obviously far from the original intention of the program.

To use the scope for statement to process multidimensional arrays, all loop control variables should be reference types except the innermost loop.

Pointer and multidimensional arrays

When the program uses the name of a multi-dimensional array, it will also automatically convert it into a pointer to the first element of the array.

When defining a pointer to a multidimensional array, don't forget that this multidimensional array is actually an array of arrays.

Because a multidimensional array is actually an array of arrays, the pointer converted from the multidimensional array name is actually a pointer to the first inner array:

int ia[3][4];//Arrays of size 3, each element is an array containing 4 integersint(*p)[4]=ia;//p points to Wu with 4 integers arrayp=&ia[2];//p points to the tail element of ia

We first make it clear (*p) means that p is a pointer. Then observe the right side and find that pointer p refers to an array with dimension 4; observe the left side and know that the elements in the array are whole
number. Therefore, p is a pointer to an array containing 4 integers.

In the above statement, brackets are essential:

int*ip[4]//Array of integer pointersint(*ip)[4];//Point to an array with 4 integers

With the introduction of the new C++11 standard, using auto or decltype can avoid adding a pointer type in front of the array as much as possible:

//Output the value of each element in a, each inner layer array takes up one row.//p points to an array containing 4 integersfor(auto p=ia;p!=ia+3;++p)
//q points to the first element of the 4 integer array, that is, q points to an integerfor(auto q=*p;q!=*p+4;++q)
cout<< *q << ' ';
cout<<endl;

The outer for loop first declares a pointer p and points to the first inner array of ia, and then iterates in turn until all 3 lines of ia are processed. The increment operation ++p is responsible for moving the pointer p to the next row of ia.

The inner layer for loop is responsible for outputting the values ​​contained in the inner layer array. It first points to the first element of the current line where p is located. *p is an array containing 4 integers. As usual, the array name is automatically converted into a reference
Pointer to the first element of the array. The inner for loop continues to iterate until we have processed all elements of the current inner array. In order to obtain the termination condition of the inner for loop, dereference p again to get a pointer to the first element of the inner array, and adding 4 to it will get the termination condition.

Of course, the same function can be achieved using the standard library functions begin and end, and it looks a bit simpler:

//p points to the first array of iafor(auto p=begin(ia);p!=end(ia);++p){
//q points to the first element of the inner layer arrayfor(auto q=begin(*p);q!=end(*p);++q)
cout<<*q<<' ';//Output the integer value referred to by qcout<<endl;

In this version of the program, the loop termination condition is determined by the end function. Although we can also infer that the type of p is a pointer to an array containing 4 integers and the type of a is a pointer to an integer, we don't have to worry about what these types are using the auto keyword.

Type alias simplify pointers to multidimensional arrays

Reading, writing, and understanding a pointer to a multidimensional array is annoying job, and using type alias can make this work a little easier, for example:

using int_array=int[4];//Declaration of type alias under the new standardtypedef int int_array[4];//Equivalent typedef statement//Output the value of each element in ia, each inner layer array takes up one rowfor(int_array * p=ia;p!=ia+3;++p){
    for(int*q=p;q!=*p+4;++q)
    cout<<*q<< ' ';
    cout<<endl;
}

Program Type“4an array of integers“and nameint_array,Use type nameint_arrayDefining control variables for outer loops makes the program look concise and clear。

This is the end of this article about the use of C++ Primer multi-dimensional arrays. For more related C++ multi-dimensional array content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!