C++11之基于范围的for循环(影响面广)

在Java语言中已有基于范围的for循环了,C++98中的fo循环与其比较,使用上繁琐。C++11则引入了基于范围的for循环,使程序变得更加简洁。

一、几组示例:

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

int opera1(int &i) { i *= 10;}
int opera2(int &i) { cout << i << '\t';}

int main()
{
    // C++98标准for循环
    int array1[5] = {1, 2, 3, 4, 5};
    int *pa;
    for(pa = array1; pa<array1+sizeof(array1)/sizeof(int); ++pa)
        *pa *= 10;
    for(pa = array1; pa<array1+sizeof(array1)/sizeof(int); ++pa)
        cout << *pa << '\t'; 
    cout << endl;

    // C++98 STL库循环
    int array2[5] = {1, 2, 3, 4, 5};
    for_each(array2, array2+sizeof(array2)/sizeof(int), opera1);
    for_each(array2, array2+sizeof(array2)/sizeof(int), opera2);
    cout << endl;

    // C++11标准基于范围的for循环
    int array3[5] = {1, 2, 3, 4, 5};
    for(int &i: array3)
        i *= 10;
    for(int i: array3)
        cout << i << '\t';
    cout << endl;
 
    // C++98标准模板中使用循环
    vector<int> iv1 = {1, 2, 3, 4, 5};
    for(auto it = iv1.begin(); it<iv1.end(); ++it)
        *it *= 10;
    for(auto it = iv1.begin(); it<iv1.end(); ++it)
        cout << *it << '\t';
    cout << endl;


    // C++11标准基于范围的for循环
    vector<int> iv2 = {1, 2, 3, 4, 5};
    for(auto &it: iv2)  // 如果auto it,则值不会改变!
        it *= 10;
    for(auto it: iv2 )
        cout << it << '\t';
    cout << endl;
    return 1;
}

一切都在不言中,C++11的基于范围的for循环给我们带来了福音!


二、注意事项:

2.1、C++11基于范围的for循环由两部分组成,之间用":"分离,前面是范围内迭代的变量,后面是被迭代的范围,如果要修改迭代范围内的数值,前一项就要使用引用或指针。

2.2、被迭代的范围一定要是确定的且满足++、--操作,STL中的容器和基本类型数组均自动满足,自定义类则要对相关操作符进行重载。关于范围确定,可看如下代码:

int array[] = {1, 2, 3, 4 ,5};

for(int i: array)

cout << i << '\t';

cout << endl;

C++11标准编译不会通过!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值