c foreach循环

介绍 (Introduction)

The foreach loop in C++ or more specifically, range-based for loop was introduced with the C++11. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator. So let us dig into the respective foreach loop structure.

C ++ 11中引入了foreach循环,或更具体地说, 基于范围的for循环 。 这种类型的for循环结构简化了对可迭代数据集的遍历。 它通过消除初始化过程并遍历每个元素而不是遍历迭代器来做到这一点。 因此,让我们深入研究各自的foreach循环结构。

C ++中的foreach循环工作 (Working of the foreach loop in C++)

So basically a for-each loop iterates over the elements of arrays, vectors, or any other data sets. It assigns the value of the current element to the variable iterator declared inside the loop. Let us take a closer look at the syntax:

因此,基本上每个循环都遍历数组 , 向量或任何其他数据集的元素。 它将当前元素的值分配给循环内声明的变量迭代器。 让我们仔细看一下语法:


for(type variable_name : array/vector_name)
{loop statements...
}

As we can see:

如我们所见:

  • During the loop initialization, the elemental variable declaration is the part where we need to declare the variable which will iterate over the array or vector. Here, the type is the data type of the variable_name在循环初始化期间, 元素变量声明是我们需要声明将在数组或向量上迭代的变量的部分。 在这里, typevariable_name的数据类型
  • array/vector name is the name of the respective data set over which the loop will iterate,数组/向量名称是循环将在其上进行迭代的各个数据集的名称,
  • loop statements are the different operations which the user can choose to perform over the corresponding elements with the use of the iterating variable.循环语句是用户可以使用迭代变量选择对​​相应元素执行的不同操作。

Note: It is suggested to keep the data type of the variable the same as that of the array or vector. If the data type is not the same, then the elements are going to be type-casted and then stored into the variable.

注意:建议使变量的数据类型与数组或向量的数据类型相同。 如果数据类型不同,则元素将被类型转换,然后存储到变量中。

foreach循环的例子 (Examples of foreach loop)

1. C ++中的数组foreach循环示例 (1. Example of foreach loop for Arrays in C++)

The code given below illustrates the use of the for-each loop in C++,

下面给出的代码说明了C ++中for-each循环的用法,


#include<iostream>
using namespace std;
int main()
{ int arr[]={1,2,3,4,5};   //array initializationcout<<"The elements are: ";for(int i : arr){cout<<i<<" ";}return 0;
}

Output:

输出


The elements are: 1 2 3 4 5

Let’s break down the code and look at it line-by-line:

让我们分解代码,逐行看一下:

  • An array arr[] is initialized with some values {1 , 2 , 3 , 4 , 5}数组arr[]被初始化为一些值{1、2、3、4、5}
  • Inside the loop structure, ‘i’ is the variable that stores the value of the current array element在循环结构内部, “ i”是存储当前数组元素值的变量
  • arr is the array name which also serves as the base address of the respective arrayarr是数组名称,它也用作相应数组的基地址
  • As we can see, printing ‘i’ for each iteration gives us the corresponding array elements in contrast to the array indices in case of normal for loop如我们所见,在正常的for循环的情况下,每次迭代打印'i'会给我们相应的数组元素,而不是数组索引

Please note: While declaring the variable ‘i‘ we could also use the auto datatype instead of int. This ensures that the type of the variable is deduced from the array type, and no data type conflicts occur.

请注意 :在声明变量' i '时,我们也可以使用auto数据类型代替int 。 这样可以确保从数组类型推导变量的类型,并且不会发生数据类型冲突。

For example:

例如:


#include<iostream>
using namespace std;
int main()
{ int array[]={1,4,7,4,8,4};cout<<"The elements are: ";for(auto var : array){cout<<var<<" ";}return 0;
}

Output:

输出

Foreach loop Using Auto data type
Foreach循环使用自动数据类型

2. C ++中向量的foreach循环示例 ( 2. Example of foreach loop for Vectors in C++ )

The following code illustrates the use of the for-each loop for iterating over a vector.

以下代码说明了for-each循环在vector进行迭代的用法。


#include<iostream>
#include<vector>
using namespace std;
int main()
{ vector<int> vec={11,22,33,44,55,66};cout<<"The elements are: ";for(auto var : vec){cout<<var<<" ";}return 0;
}

Output:

输出

Foreach For Vectors
向量的Foreach

The for-each loop for vector works in the same way as it does for an array. Furthermore, the only differences are the vector declaration, initialization and the different operations that can be performed over it.

向量的for-each循环的工作方式与数组相同。 此外,唯一的区别是向量声明,初始化以及可以对其执行的不同操作。

C ++中foreach循环的优缺点 (Advantages and Disadvantages of the foreach loop in C++)

1. foreach循环的优点 (1. Advantages of foreach loop)

  • It eliminates the possibility of errors and makes the code more readable.它消除了错误的可能性,并使代码更具可读性。
  • Easy to implement易于实施
  • Does not require pre-initialization of the iterator不需要预先初始化迭代器

2. foreach循环的缺点 (2. Disadvantages of foreach loop)

  • Cannot directly access the corresponding element indices无法直接访问相应的元素索引
  • Cannot traverse the elements in reverse order无法以相反顺序遍历元素
  • It doesn’t allow the user to skip any element as it traverses over each one of them它不允许用户跳过任何遍历每个元素的元素

结论 (Conclusion)

The foreach loop in C++ has its own pros and cons. The code is easy to read but it restricts some of the actions that the normal for loop offers. Hence, it completely depends on the user what he/she wants the loop to perform and choose accordingly.

C ++中foreach循环有其优点和缺点。 该代码易于阅读,但是它限制了普通for循环提供的某些操作。 因此,这完全取决于用户他/她希望循环执行什么并相应地选择。

参考资料 (References)

  • https://stackoverflow.com/questions/16504062/how-to-make-the-for-each-loop-function-in-c-work-with-a-custom-classhttps://stackoverflow.com/questions/16504062/how-to-make-the-for-each-loop-function-in-c-work-with-a-custom-class

翻译自: https://www.journaldev.com/36227/foreach-loop-c-plus-plus

c foreach循环

c foreach循环_C ++中的foreach循环相关推荐

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

    for-each 循环 C ++中基于范围的循环(增强了循环) (Range-based loop in C++ (enhanced for loop)) for loop is used to ex ...

  2. c#foreach循环_C#| 使用foreach循环打印整数数组

    c#foreach循环 Given an integer array and we have to print its elements using "foreach loop" ...

  3. java foreach标签_Java中Velocity foreach循环标签详解

    Java中Velocity foreach循环标签详解 Java Velocity中foreach循环可以很容易的遍历数组或者集合. 定义 #foreach( $elem in $allElems) ...

  4. php中的foreach和js中的foreach的用法和区别

    PHP中的foreach循环: 主要用于遍历数组 例如: (1)// $colors=array("red","yellow","blue" ...

  5. php循环套循环_PHP中的事件循环简介

    php循环套循环 PHP developers are always waiting for something. Sometimes we're waiting for requests to re ...

  6. csh for循环_shell中的for循环用法详解_linux shell

    这篇文章主要介绍了shell中的for循环用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧 for 命令: for i i ...

  7. mysql的for循环_MySQL中的For循环示例

    三国纷争 MySQL中的while循环语法示例:delimiter //CREATE procedure yourdatabase.while_example()wholeblock:BEGIN  d ...

  8. continue语句只用于循环语句中_Java之循环语句、条件判断语句(三目运算符)、break、continue...

    之前的内容只是让读者可以定义变量,输出变量等基础功能而已.这远远是不够的,今天,我们学习的内容可以帮你开始完善自己想开发的内容,在这之前我们先理解一个概念:一个表达式的返回值是布尔值的表达式称为布尔 ...

  9. python提前结束本层循环_python中退出多层循环的方法

    1.定义标记变量:利用变量值的变化退出循环 # 第一种嵌套形式 a = [[1, 2, 3], [5, 5, 6], [7, 8, 9]] # init_i = 0 # init_j = 0 flag ...

最新文章

  1. 初次使用Windbg调试简单C++程序
  2. 深大教授开源的人脸检测库,速度号称史上最快
  3. 【Linux 】使用 Shell 批量重命名文件名称
  4. linun——SElinux的简单理解
  5. 小米无法链接华硕路由器_2000元的华硕电竞路由器开箱,如此高贵,体验是怎样的?...
  6. 通用业务流水号功能设计
  7. 光进铜退下的“更高”与“更低”,锐捷发布企业极简以太全光网解决方案
  8. 【已作废】基于Freeswitch的ASTPP计费系统的安装 (CentOS 7)
  9. Web前端开发:SQL Jsp小项目(一)
  10. android逆透视变换坐标,android – 如何使用OpenGL模拟OpenCV的warpPerspective功能(透视变换)...
  11. 蓝桥杯 基础练习 龟兔赛跑预测
  12. 遍历~筛选~eq();filter();first();last();has();is();map();slice()
  13. MyBatis3与Spring3的整合配置(初级篇)
  14. 计算机毕业设计python基于django租房系统-房屋租赁系统
  15. flash写保护原理_Flash存储原理
  16. 为什么打工人 996 会猝死,而企业家 007 却不会?
  17. VBS学习笔记(4): WScript //d //x MyScript.vbs,调试无法启动
  18. OSChina 周六乱弹 —— 我都想和他们组成一个家庭了
  19. python爬虫之淘宝秒抢软件
  20. 进程之间的通信方式有哪些?

热门文章

  1. dynamic结合匿名类型 匿名对象传参
  2. Touch事件分发源码解析
  3. 【CNN】 吴恩达课程中几种网络的比较
  4. maven安装的详细步骤
  5. 头条号【编编成程】开通
  6. MySQL的UNIQUE KEY对数据中字母的大小写不敏感
  7. 【已解决】关于SQL2008 “不允许保存更改。您所做的更改要求删除并重新创建以下表。您对无法重新创建的标进行了更改或者启用了‘阻止保存要求重新创建表的更改’” 解决方案...
  8. struts2学习笔记(2)
  9. JavaScript 弹出层,背景变暗
  10. exchange EWS 开发随笔二