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!
CodePudding user response:
In
for (int& x[] : a)
x
is an array of references. Arrays of references are not legal C .The type is
int[2]
.You can avoid
auto
by writingfor (int (&x)[2] : a)
. The extra parentheses around&x
are crucial, without the parens you have an array of references (not legal), with the parens you have a reference to an array.
CodePudding user response:
As john noted:
#include <iostream>
int a[][2] = { {2,2}, {3,3}, {4,4} };
int main()
{
for (int(&x)[2] : a) // one row at a time
{
for (int x2 : x) // print each col in row
{
std::cout << x2 << " ";
}
std::cout << '\n';
}
}
or, just use auto
#include <iostream>
int a[][2] = { {2,2}, {3,3}, {4,4} };
int main()
{
for (auto& x: a) // one row at a time
{
for (auto x2 : x) // print each col in row
{
std::cout << x2 << " ";
}
std::cout << '\n';
}
}