So I’m reading C++ Primer, and I arrive at exercise 3.43 in which I’m supposed to make a program that prints all the elements in an array without using auto – I’m pretty sure this kinda goes against the point of using a range-based for loop, but I think the goal is to understand and learn to explicitly declare confusing variables such as pointers and references. So I write the program:
#include <iostream>
char ia[3][4] = {{'q', 'w', 'e', 'r'}, {'t', 'y', 'u', 'i'}, {'o', 'p', 'a', 's'}};
int main ()
{
for (char &row : *ia)
for (char &col : &row)
std::cout << col << std::endl;
return 0;
}
But even thought the first for loop seems fine, the second, innermost loop claims there is no suitable begin declaration and the program won’t compile. Why?
I’m still new to range-based for loops, but if my understanding is correct: I need to pass row and col as references so they don’t get automatically converted to pointers by the compiler because that’s how arrays work (how quirky!), and similarly since ia would be passed as a pointer to its first element I need to dereference it so it gets passed as the actual element of the array (which is another array since that’s how multidimensional arrays work).
That way I’m essentially telling the program: for every row in the array, go through this column, and for every column, (since each column contains one element) print this column.
But the program still insists:
"begin was not declared for this scope."
Is there something wrong with my declarations?
>Solution :
The problem:
There are 2 issues in your code, both in the first loop:
- The whole 2D array is
ianot*ia. - The type of the ranged loop element is
char[4].
A fixed version:
#include <iostream>
int main()
{
char ia[3][4] = { {'q', 'w', 'e', 'r'}, {'t', 'y', 'u', 'i'}, {'o', 'p', 'a', 's'} };
using CharArr4 = char[4];
for (CharArr4 const& row : ia)
{
for (char const& col : row)
{
std::cout << col << std::endl;
}
}
return 0;
}
Notes:
- I used a
usingstatement to define thechar[4]type to make it more readable. - I used
constfor the types of the elements of the loop since you do not modify them. - There’s no reason for
iato be global (although in this case it can work as well).
Output:
q
w
e
r
t
y
u
i
o
p
a
s