The only difference between the following two snippets of code is the usage of reference. I understand why the first snippet does not compile and am seeking help in understanding why the second one compiles.
The first snippet:
int a[2][3] = {0,1,2,3,4,5};
for (auto row : a)
for (auto column : row)
cout << column << endl;
The above code does not compile because the type of 'row' is pointer to int, which is not a sequence.
The second snippet:
int a[2][3] = {0,1,2,3,4,5};
for (auto &row : a)
for (auto column : row)
cout << column << endl;
This code compiles. If I understand correctly how auto works, 'row' is a reference to pointer to int. But why can this reference be viewed as a sequence more than a regular pointer?
Range-based for loop (since C++11) Executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
C++11 introduced the ranged for loop. This for loop is specifically used with collections such as arrays and vectors. For example, // initialize an int array int num[3] = {1, 2, 3}; // use of ranged for loop for (int var : num) { // code } Here, the ranged for loop iterates the array num from beginning to end.
Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .
Deduction of the type is done via template argument deduction.
template <typename U>
void foo(U&); // Equivalent to auto&
foo(row);
This will always deduce U
to be the exact type of row
(if it's an lvalue as in this case), which gives us the array type we desired.
Only for non-reference parameters is the array-to-pointer decay performed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With