如何为基础的范围内,为普通阵列的工作? [英] How does the range-based for work for plain arrays?

查看:123
本文介绍了如何为基础的范围内,为普通阵列的工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆