cplus 11 中for循环新增的用法(基于范围的for循环)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_22642239/article/details/102742679

for循环在c++中很常见,在c++11中新增了for的用法,我也是在最近看代码的时候遇见的,在for循环新增的功能中也涉及到了c++11新增的auto,可以自动获取变量类型。

以前的用法

for(表达式1;表达式2;表达式3)
{
    //循环的内容
}

c++11中的用法:

for 语句允许简单的范围迭代:

int my_array[5] = {1, 2, 3, 4, 5};
// 每个数组元素乘于 2
for (int &x : my_array)
{
    x *= 2;
    cout << x << endl;  
}
// auto 类型也是 C++11 新标准中的,用来自动获取变量的类型
for (auto &x : my_array) {
    x *= 2;
    cout << x << endl;  
}

上面for述句的第一部分定义被用来做范围迭代的变量,就像被声明在一般for循环的变量一样,其作用域仅只于循环的范围。而在":"之后的第二区块,代表将被迭代的范围。

示例:

#include<iostream>  
#include<string>  
#include<cctype>  
using namespace std;  
  
int main()  
{  
    string str("some string");  
    // range for 语句  
    for(auto &c : str)  
    {  
        c = toupper(c);  
    }  
    cout << str << endl;  
    return 0;  
}

上面的程序使用Range for语句遍历一个字符串,并将所有字符全部变为大写,然后输出结果为:

SOME STRING

猜你喜欢

转载自blog.csdn.net/qq_22642239/article/details/102742679