It works for any expression whose type is an array. For example:
int (*arraypointer)[4] = new int[1][4]{{1, 2, 3, 4}};
for(int &n : *arraypointer)
n *= 2;
delete [] arraypointer;
For a more detailed explanation, if the type of the expression passed to the right of :
is an array type, then the loop iterates from ptr
to ptr + size
(ptr
pointing to the first element of the array, size
being the element count of the array).
This is in contrast to user defined types, which work by looking up begin
and end
as members if you pass a class object or (if there is no members called that way) non-member functions. Those functions will yield the begin and end iterators (pointing to directly after the last element and the begin of the sequence respectively).
This question clears up why that difference exists.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…