New features of C++11 (12) - use auto to represent multidimensional array pointers

pointer to multidimensional array


A multidimensional array is a common data structure that is actually an array of arrays. Although this meaning is well understood, it is a bit troublesome when defining pointers that manipulate array data. Suppose you have the following two-dimensional array.


int matrix[10][10];


Which of the following is the correct way to define a pointer to one of the rows?


int *row[10];

int (*row)[10];


The answer is the second. Of course, it is a way to memorize it here, but you can also look at the code in another way:


int*   row[10];

int(*row)[10];   


The first case is an array of pointers, and the rest is an array of pointers.


How C++11 handles it


After C++11, with auto descriptors and begin/end functions, it is easier to define pointers to multidimensional arrays. For example, you can write code like this:


int matrix[10][10];

int number =1; 

for(auto row = begin(matrix); row != end(matrix); ++row)

 {

       for(auto data = begin(*row); data != end(*row); ++data){

           *data = number++;

       }

 }


Because row is an array pointer, and begin and end require a reference type, the parameter used when calling the begin and end functions to obtain the data pointer is *row, not row.


Other than that, it's all natural.


Author's point of view


Today's description is not so much a new content as it is a comprehensive exercise of the previous content.


Found this article helpful? Please share with more people.
To read more updated articles, please scan the QR code below and follow the WeChat public account [Object-Oriented Thinking]

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325915630&siteId=291194637