C++11for循环的一种特殊写法

本文探讨了C++1.0与C++11 for循环的对比,介绍了新版for循环的简洁写法,以及其背后的编译原理。重点讲解了C++2.0中使用范围-based for循环处理数组、vector和自定义类型的情况,以及遇到的类型转换限制。
摘要由CSDN通过智能技术生成

C++1.0的for循环写法是这样的:

#include <iostream>
using namespace std;

int main()
{
    int n[10]{1,2,3,4,6,8,9,0}; //后面几位会用0补充
    for(int i = 0; i < 10; i++) 
    {
        cout<<n[i]<<endl;
    }
}

C++2.0(C++11)新版的for循环是这样的:

#include <iostream>
#include <vector>

using namespace std;

int main()
{

    for(int i :{1,2,3,4,6,8,9})
    {
        cout<<i<<endl;
    }

    cout<<"------------"<<endl;
    int n[10]{5,8};
    for(int i : n)
    {
        cout<<i<<endl;
    }

    cout<<"------------"<<endl;
    vector<string> vec{"hello","Gentle","give me a like"};

    for(auto a : vec)
    {
        cout<<a<<endl;
    }
    
      cout<<"------------"<<endl;
    for(auto& a: vec)
    {
        a += "hhh";
    }
    for(const auto& a : vec)
    {
        cout<<a<<endl;
    }
}

运行结果:
在这里插入图片描述
新版的for循环代码简洁,让人舒服,特别在写迭代器时,我知道这种写法后就一直用了,fall In love for it。

这简单的操作背后编译器做了些什么动作了呢?

仔细看图:
在这里插入图片描述
左边是我们用的for循环,右边是它的底层实现。
注意当元素在for循环中初始化为decl时,不可能进行显式类型转换。
如下代码:

#include <iostream>
#include <vector>

using namespace std;

class C
{
public:
    explicit C(const string &s);
};

int main()
{
    vector<string> vs{"AA","BB","CC"};
    for(const C& elem : vs) //ERROR 没有定义从字符串到C的转换
    {
        cout<<elem<<endl;
    }

}

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

困了就喝白茶

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值