普通数组的基于范围的工作如何? [英] How does the range-based for work for plain arrays?

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

问题描述

在 C++11 中,您可以使用基于范围的 for,它充当其他语言的 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;
}

它怎么知道什么时候停止?它是否仅适用于在使用 for 的同一范围内声明的静态数组?您将如何将此 for 与动态数组一起使用?

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?

推荐答案

它适用于任何类型为数组的表达式.例如:

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;

更详细的解释,如果传递给:右边的表达式的类型是数组类型,那么循环从ptr迭代到ptr + size (ptr 指向数组的第一个元素,size 是数组的元素个数).

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).

这与用户定义类型形成对比,用户定义类型通过查找 beginend 作为成员来工作,如果你传递一个类对象或者(如果没有成员调用这样)非成员函数.这些函数将产生开始和结束迭代器(分别指向最后一个元素和序列的开始之后).

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.

这篇关于普通数组的基于范围的工作如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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