I was practicing array problems and I stuck by this one:
Given a declaration of 2D array:
int a[][2] = { {2,2}, {3,3}, {4,4} };
write a nested for loop to print all the values of a.
First, since 2D array is an array of rows (means each element of this array is a row vector),
I tried a for loop like this:
for (int& x[]: a)
for (int y: x)
cout << y << " ";
The outer for-loop means I want to reference each row of a, give it a name "x"; the inner for-loop means I want to reference each element of x, give it a name "y".
I thought the declaration in the outer for-loop is valid as I specified x as array in integer type, but error showed up while compiling.
I checked out the solution and it indicated that x has to be declared as auto type,
which means I should write the outer loop as " for(auto& x: a)
".
The solution also indicated that this is the only way, but I was not sure whether it is true or not.
Hence, I want to figure out couple things:
- Why it was not working when I wrote a line like "
for (int& x[]: a)
" ? - What is the data type of x in the line "
for (auto& x : a)
" ? What did auto detected? - Is using auto really the only way in this situation?
Thank you!