for-each 循环_C ++中基于范围的循环(类似于for-each循环)

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 循环

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值