解析C++中的for循环以及基于范围的for语句使用

 更新时间:2016年01月16日 17:01:05   投稿:goldensun  
这篇文章主要介绍了解析C++中的for循环以及基于范围的for语句使用,是C++入门学习中的基础知识,需要的朋友可以参考下

for循环语句

重复执行语句,直到条件变为 false。

语法

for ( init-expression ; cond-expression ; loop-expression ) 
  statement;

备注
使用 for 语句可构建必须执行指定次数的循环。
for 语句包括三个可选部分,如下表所示。
for 循环元素

2016116165838737.png (878×231)

下面的示例将显示使用 for 语句的不同方法。

#include <iostream>
using namespace std;

int main() {
  // The counter variable can be declared in the init-expression.
  for (int i = 0; i < 2; i++ ){ 
    cout << i;
  }
  // Output: 01
  // The counter variable can be declared outside the for loop.
  int i;
  for (i = 0; i < 2; i++){
    cout << i;
  }
  // Output: 01
  // These for loops are the equivalent of a while loop.
  i = 0;
  while (i < 2){
    cout << i++;
  }
}
  // Output: 012
init-expression 和 loop-expression 可以包含以逗号分隔的多个语句。例如:


#include <iostream>
using namespace std;

int main(){
  int i, j;
  for ( i = 5, j = 10 ; i + j < 20; i++, j++ ) {
    cout << "i + j = " << (i + j) << '\n';
  }
}
  // Output:
  i + j = 15
  i + j = 17
  i + j = 19


loop-expression 可以递增或递减,或通过其他方式修改。

#include <iostream>
using namespace std;

int main(){
for (int i = 10; i > 0; i--) {
    cout << i << ' ';
  }
  // Output: 10 9 8 7 6 5 4 3 2 1
  for (int i = 10; i < 20; i = i+2) {
    cout << i << ' ';
  }
  // Output: 10 12 14 16 18


当 statement 中的 break、return 或 goto(转到 for 循环外部的标记语句)执行时,for 循环将终止。 for 循环中的 continue 语句仅终止当前迭代。
如果忽略 cond-expression,则认为其为 true,for 循环在 statement 中没有 break、return 或 goto 时不会终止。
虽然 for 语句的三个字段通常用于初始化、测试终止条件和递增,但并不限于这些用途。例如,下面的代码将打印数字 0 至 4。在这种情况下,statement 是 null 语句:

#include <iostream>
using namespace std;

int main()
{
  int i;
  for( i = 0; i < 5; cout << i << '\n', i++){
    ;
  }
}


for 循环和 C++ 标准
C++ 标准中提到,for 循环中声明的变量将在 for 循环结束后超出范围。例如:


for (int i = 0 ; i < 5 ; i++) {
  // do something
}
// i is now out of scope under /Za or /Zc:forScope

默认情况下,在 /Ze 下,for 循环中声明的变量在 for 循环的封闭范围终止前保持在范围内。
/Zc:forScope 无需指定 /Za 即可启用 for 循环中声明的变量的标准行为。
也可以使用 for 循环的范围差异,重新声明 /Ze 下的变量,如下所示:

// for_statement5.cpp
int main(){
  int i = 0;  // hidden by var with same name declared in for loop
  for ( int i = 0 ; i < 3; i++ ) {}

  for ( int i = 0 ; i < 3; i++ ) {}
}


这更类似于 for 循环中声明的变量的标准行为,后者要求 for 循环中声明的变量在循环完毕后超出范围。在 for 循环中声明变量后,编译器会在内部将其提升为 for 循环封闭范围中的局部变量,即使存在同名的局部变量也会如此。

基于范围的 for 语句
语句 statement 按顺序反复执行语句 expression 中的每个元素。
语法

  for ( for-range-declaration : expression )
statement 

备注
使用基于范围的 for 语句构造一个必须执行的循环范围,可以定义为任意一个循环访问,例如 std::vector,或者其他任意用 begin() 和 end()定义的范围。命名在 for-range-declaration 语句是属于 for 的,不能在 expression 或 statement中再次声明。请注意 自动 关键字是在 for-range-declaration 中部分语句的首选。
这段代码展示了如何使用 for 范围的循环来遍历数组和向量:

// range-based-for.cpp
// compile by using: cl /EHsc /nologo /W4
#include <iostream>
#include <vector>
using namespace std;

int main() 
{
  // Basic 10-element integer array.
  int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

  // Range-based for loop to iterate through the array.
  for( int y : x ) { // Access by value using a copy declared as a specific type. 
            // Not preferred.
    cout << y << " ";
  }
  cout << endl;

  // The auto keyword causes type inference to be used. Preferred.

  for( auto y : x ) { // Copy of 'x', almost always undesirable
    cout << y << " ";
  }
  cout << endl;

  for( auto &y : x ) { // Type inference by reference.
    // Observes and/or modifies in-place. Preferred when modify is needed.
    cout << y << " ";
  }
  cout << endl;

  for( const auto &y : x ) { // Type inference by reference.
    // Observes in-place. Preferred when no modify is needed.
    cout << y << " ";
  }
  cout << endl;
  cout << "end of integer array test" << endl;
  cout << endl;

  // Create a vector object that contains 10 elements.
  vector<double> v;
  for (int i = 0; i < 10; ++i) {
    v.push_back(i + 0.14159);
  }

  // Range-based for loop to iterate through the vector, observing in-place.
  for( const auto &j : v ) {
    cout << j << " ";
  }
  cout << endl;
  cout << "end of vector test" << endl;
}


输出如下:

1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
end of integer array test
0.14159 1.14159 2.14159 3.14159 4.14159 5.14159 6.14159 7.14159 8.14159 9.14159
end of vector test

一个基于 for 循环终止于 statement 执行完成: break, return,或者 goto 转到一个语句外的 for 循环 continue 与语句终止当前 for 循环的迭代。
记住这些关于范围 for 的事实
自动识别数组。
识别那些有 .begin() 和 .end() 的容器。
使用基于自变量的查找 begin() 和 end() 。

相关文章

  • C语言算法练习之求二维数组最值问题

    C语言算法练习之求二维数组最值问题

    这篇文章主要为大家介绍了C语言算法练习中求二维数组最值的实现方法,文中的示例代码讲解详细,对我们学习C语言有一定帮助,需要的可以参考一下
    2022-09-09
  • C语言实现经典windows游戏扫雷的示例代码

    C语言实现经典windows游戏扫雷的示例代码

    今天我们会用C语言实现一个经典的windows小游戏:扫雷。扫雷是一款单机小游戏,每次通关最高难度的关卡都会开心好一阵。现在学会了C语言,总算可以自己实现扫雷了。话不多说,咱们开始吧
    2022-10-10
  • C++算法设计之马踏棋盘的实现

    C++算法设计之马踏棋盘的实现

    这篇文章主要为大家详细介绍了C++算法设计之马踏棋盘的实现,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-02-02
  • C语言类型转换与常量的细节深入理解探究

    C语言类型转换与常量的细节深入理解探究

    这篇文章主要为大家介绍了C 语言类型转换与常量的细节深入理解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-12-12
  • COLORREF,COLOR,RGB,CString的转化总结分析

    COLORREF,COLOR,RGB,CString的转化总结分析

    实际的软件开发过程中,常需要用到非.net平台的代码。这时候就可能碰到ColorRef(也就是以int类型代表的颜色值或是以DWORD值表示的颜色)。这跟.net平台下的颜色的相互转换MS并没有直接实现
    2013-09-09
  • C语言实现贪吃蛇小游戏开发

    C语言实现贪吃蛇小游戏开发

    这篇文章主要为大家详细介绍了C语言实现贪吃蛇小游戏开发,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-08-08
  • c++ 开发中如何读写yaml配置文件

    c++ 开发中如何读写yaml配置文件

    这篇文章主要介绍了c++ 开发中如何读写yaml配置文件,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2023-04-04
  • 探讨C语言的那些小秘密之断言

    探讨C语言的那些小秘密之断言

    我尽可能的把我所理解的断言的使用讲解清楚,希望我在此所讲的断言能够对你有所帮助,让你以后能够在代码中灵活使用断言
    2013-09-09
  • C/C++ Qt QThread线程组件的具体使用

    C/C++ Qt QThread线程组件的具体使用

    QThread库是QT中提供的跨平台多线程实现方案,本文详细的介绍了Qt QThread线程组件的具体使用,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2021-11-11
  • OpenCV利用K-means实现根据颜色进行图像分割

    OpenCV利用K-means实现根据颜色进行图像分割

    K-means是一种经典的无监督聚类算法---不需要人工干预。本文将通过K-means算法实现根据颜色进行图像分割的效果,感兴趣的小伙伴可以尝试一下
    2022-10-10

最新评论