基于范围的 for 语句 (C++)
对 statement
中的每个元素按顺序重复执行 expression
。
语法
for (
for-range-declaration:
expression)
语句
备注
使用基于范围的 for
语句构造必须在“范围”中执行的循环,它定义为可循环访问的任何内容 - 例如,std::vector
或其范围由 begin()
和 end()
定义的任何其他 C++ 标准库序列。 for-range-declaration
部分中声明的名称是 for
语句的本地名称,且无法在 expression
或 statement
中重新声明它。 请注意,在语句的 for-range-declaration
部分中,auto
关键字是首选的。
Visual Studio 2017 中的新增功能:基于范围的 for
循环不再需要 begin()
和 end()
返回相同类型的对象。 这使得 end()
能够返回类似于 Ranges-V3 方案中定义的范围所使用的那种 sentinel 对象。 有关详细信息,请参阅通用化基于范围的 For
循环和 GitHub 上的 range-v3 库。
此代码说明了如何使用基于范围的 for
循环来循环访问数组和矢量:
// range-based-for.cpp
// compile by using: cl /EHsc /nologo /W4
#include <iostream>
#include <vector>
using namespace std;
int main()
{
// Basic 10-element integer array.
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 << " ";
}
cout << endl;
// The auto keyword causes type inference to be used. Preferred.
for( auto y : x ) { // Copy of 'x', almost always undesirable
cout << y << " ";
}
cout << endl;
for( auto &y : x ) { // Type inference by reference.
// Observes and/or modifies in-place. Preferred when modify is needed.
cout << y << " ";
}
cout << endl;
for( const auto &y : x ) { // Type inference by const reference.
// Observes in-place. Preferred when no modify is needed.
cout << y << " ";
}
cout << endl;
cout << "end of integer array test" << endl;
cout << endl;
// Create a vector object that contains 10 elements.
vector<double> v;
for (int i = 0; i < 10; ++i) {
v.push_back(i + 0.14159);
}
// Range-based for loop to iterate through the vector, observing in-place.
for( const auto &j : v ) {
cout << j << " ";
}
cout << endl;
cout << "end of vector test" << endl;
}
输出如下:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
end of integer array test
0.14159 1.14159 2.14159 3.14159 4.14159 5.14159 6.14159 7.14159 8.14159 9.14159
end of vector test
在 statement
中执行下列项之一时,基于范围的 for
循环将终止:针对基于范围的 for
循环外部的标记语句的 break
、return
或 goto
。 基于范围的 for
循环中的 continue
语句仅终止当前迭代。
请记住这些有关基于范围的 for
的情况:
自动识别数组。
识别拥有
.begin()
和.end()
的容器。对于任何其他内容,使用依赖于自变量的查找
begin()
和end()
。
另请参阅
反馈
https://aka.ms/ContentUserFeedback。
即将发布:在整个 2024 年,我们将逐步淘汰作为内容反馈机制的“GitHub 问题”,并将其取代为新的反馈系统。 有关详细信息,请参阅:提交和查看相关反馈