基于范围的 for 循环语句中,“范围”指可以迭代遍历各种区间,例如数组或C++ 标准库中可由begin()、end()迭代遍历的各种容器,如map、list、queue等。
下面的代码演示如何使用基于范围的 for 循环来循环访问数组:
int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Range-based for loop to iterate through the array.
for( int y : x ) { // Access by value using a copy declared as a specific type.
// Not preferred.
cout << y << " ";
}
for( auto &y : x ) { // Type inference by reference.
// Observes and/or modifies in-place. Preferred when modify is needed.
cout << y << " ";
}
基于范围的for循环中:
- 自变量类型常用 aoto
- auto y,值访问(只读); auto &y,地址访问(可写)
- 支持 break、continue、return、goto等语句