C++中使用基于范围的 for 循环

C++中使用基于范围的 for 循环

C++11 引入了一种新的 for 循环,让对一系列值(如数组包含的值)进行操作的代码更容易编写和理解。

基于范围的 for 循环也使用关键字 for:

cpp 复制代码
for (VarType varName : sequence)
{
    // Use varName that contains an element from sequence
}

例如,给定一个整型数组 someNums,可像下面这样使用基于范围的 for 循环来读取其中的元素:

cpp 复制代码
int someNums[] = { 1, 101, -1, 40, 2040 };

for (int aNum : someNums) // range based for
    cout << "The array elements are " << aNum << endl;

提示:

cpp 复制代码
通过使用关键字 auto 来自动推断变量的类型,可编写一个通用的 for 循环,对任何类型的数组 elements 进行处理,从而进一步简化前面的 for 语句:
    for (auto anElement : elements) // range based for
        cout << "Array elements are " << anElement << endl;

以下示例程序演示了如何使用基于范围的 for 循环来处理一系列不同类型的值:

cpp 复制代码
#include<iostream>
#include <string>
using namespace std;

int main()
{
   int someNums[] = { 1, 101, -1, 40, 2040 };

   for (const int& aNum : someNums) 
      cout << aNum << ' ';
   cout << endl;

   for (auto anElement : { 5, 222, 110, -45, 2017 })
      cout << anElement << ' ';
   cout << endl;

   char charArray[] = { 'h', 'e', 'l', 'l', 'o' };
   for (auto aChar : charArray) 
      cout << aChar << ' ';
   cout << endl;

   double moreNums[] = { 3.14, -1.3, 22, 10101 };
   for (auto anElement : moreNums)
      cout << anElement << ' ';
   cout << endl;

   string sayHello{ "Hello World!" };
   for (auto anElement : sayHello)
	   cout << anElement << ' ';
   cout << endl;

   return 0;
}

输出:

复制代码
1 101 -1 40 2040
5 222 110 -45 2017
h e l l o
3.14 -1.3 22 10101
H e l l o W o r l d !

分析:

这个程序清单包含多个基于范围的 for 循环实现,如第 8、 12、 17、 22 和 27 行所示。其中每个实现都使用循环将一系列内容显示到屏幕上---每次一个元素。有趣的是,虽然范围各不相同,从第 8 行的整型数组 someNums 到第 12 行未指定的范围,从第 17 行的 char 数组 charArray 到第 27 行的 std::string,但基于范围的 for 循环的语法始终相同。

这种简洁性让基于范围的 for 循环成了最受欢迎的 C++新功能之一。

在有些情况下(尤其是使用大量条件处理大量参数的复杂循环中),无法编写有效的循环条件,而需要在循环中修改程序的行为。在这种情况下, contiune 和 break 可提供帮助。

continue 让您能够跳转到循环开头,跳过循环块中后面的代码。因此,在 while、 do...while 和 for 循环中, continue 导致重新评估循环条件,如果为 true,则重新进入循环块。

而 break 退出循环块,即结束当前循环。

该文章会更新,欢迎大家批评指正。

推荐一个零声学院的C++服务器开发课程,个人觉得老师讲得不错,

分享给大家:Linux,Nginx,ZeroMQ,MySQL,Redis,

fastdfs,MongoDB,ZK,流媒体,CDN,P2P,K8S,Docker,

TCP/IP,协程,DPDK等技术内容

点击立即学习:C/C++后台高级服务器课程

相关推荐
blasit11 小时前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
肆忆_2 天前
# 用 5 个问题学懂 C++ 虚函数(入门级)
c++
不想写代码的星星2 天前
虚函数表:C++ 多态背后的那个男人
c++
端平入洛3 天前
delete又未完全delete
c++
端平入洛4 天前
auto有时不auto
c++
哇哈哈20215 天前
信号量和信号
linux·c++
多恩Stone5 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
蜡笔小马5 天前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
超级大福宝5 天前
N皇后问题:经典回溯算法的一些分析
数据结构·c++·算法·leetcode
weiabc5 天前
printf(“%lf“, ys) 和 cout << ys 输出的浮点数格式存在细微差异
数据结构·c++·算法