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++后台高级服务器课程

相关推荐
Aaswk7 分钟前
刷题笔记(回溯算法)
数据结构·c++·笔记·算法·leetcode·深度优先·剪枝
zhooyu10 分钟前
GLM中lerp实现线性插值
c++·opengl
我不是懒洋洋22 分钟前
预处理详解
c语言·开发语言·c++·windows·microsoft·青少年编程·visual studio
计算机安禾27 分钟前
【数据结构与算法】第14篇:队列(一):循环队列(顺序存储
c语言·开发语言·数据结构·c++·算法·visual studio
IT从业者张某某32 分钟前
基于EGE19.01完成恐龙跳跃游戏-V00-C++使用EGE19.01这个轮子
c++·游戏
-许平安-1 小时前
MCP项目笔记六(PluginsLoader)
c++·笔记·raii·plugin system
呜喵王阿尔萨斯1 小时前
argc & argv
c语言·c++
Vect__1 小时前
std::bind和lambda的使用
c++
她叫我大水龙2 小时前
MSYS2的C/C++,python2,python3编译环境安装脚本
c语言·c++
宵时待雨3 小时前
C++笔记归纳17:哈希
数据结构·c++·笔记·算法·哈希算法