for-each 循环
C ++中基于范围的循环(增强了循环) (Range-based loop in C++ (enhanced for loop))
for loop is used to execute a block of statements multiple times if the user knows exactly how many iterations are needed or required.
如果用户确切知道需要或需要多少次迭代,则使用for循环多次执行语句块。
After the release of C++ 11, it supports an enhanced version of for loop, which is also called for-each loop or enhanced for loop. This loop works on iterable like string, array, sets, etc.
C ++ 11发行后,它支持for循环的增强版本,也称为for-each循环或增强的for循环 。 此循环适用于可迭代的字符串,数组,集合等。
Syntax of range-based (for-each/enhanced for loop):
基于范围的语法(for-each / enhanced for loop):
for (data_type variable : iterable){
//body of the loop;
}
It stores each item of the collection in variable and then executes it.
它将集合的每个项目存储在变量中,然后执行它。
Note: auto keyword can be used instead of data_type which automatically deduce the type of the element. So type error can be reduced.
注意:可以使用auto关键字代替data_type ,它会自动推断元素的类型。 因此可以减少类型错误。
C ++代码演示基于范围的循环的示例 (C++ code to demonstrate example of range-based loop)
// C++ program to demonstrate example of
// range-based loop (for-each/ enhanced for loop)
#include <iostream>
using namespace std;
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9};
cout << "\n Demonstration of for-each in C++" << endl;
// Notice that instead of int, auto is used
// it automatically checks for the type of
// the variable so type error can be reduced
// using auto keyword
for (auto x : arr){
cout << " " << x << endl;
}
return 0;
}
Output
输出量
Demonstration of for-each in C++
1
2
3
4
5
6
7
8
9
翻译自: https://www.includehelp.com/stl/range-based-loop-in-cpp-similar-to-for-each-loop.aspx
for-each 循环