如何为基础的范围内,为普通阵列的工作? [英] How does the range-based for work for plain arrays?
问题描述
在C ++ 11可以使用一系列基于为
,它充当的foreach
其他语言。它的工作原理,即使普通的C数组:
In C++11 you can use a range-based for
, which acts as the foreach
of other languages. It works even with plain C arrays:
int numbers[] = { 1, 2, 3, 4, 5 };
for (int& n : numbers) {
n *= 2;
}
它是如何知道什么时候停止?它只能和那些在同一范围内的为
是用在被宣布静态数组工作?你将如何使用该为
动态数组?
How does it know when to stop? Does it only work with static arrays that have been declared in the same scope the for
is used in? How would you use this for
with dynamic arrays?
推荐答案
它适用于任何前pression其类型是一个数组。例如:
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;
有关更详细的解释,如果EX pression类型传递到右侧:
是一个数组类型,然后从<$循环迭代C $ C> PTR 到 PTR +尺寸
( PTR
指向的第一个元素数组,尺寸
作为数组的元素计)。
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).
<一个href=\"http://stackoverflow.com/questions/2648878/range-based-for-statement-definition-redundancy\">This问题清除了为什么会存在差异。
This question clears up why that difference exists.
这篇关于如何为基础的范围内,为普通阵列的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!