C11新特性:2.range-based for loop

本文介绍C11标准中新增的范围for循环语法及其使用方式,包括对不同数据结构的支持,如STL容器、初始化列表及C风格数组,并提醒开发者注意隐式转换的问题。

c11中提供一种新的for循环

for(auto item : collection){
    statement;
}

该语句等价于:

for(auto index = collection.begin();index != collection.end();index++){
    item = *index;
    statement;
}

如果collection没有begin或者end成员函数,则等价于:

for(auto index = begin(collection); index != end(collection); index++){
    item = *index;
    statement;
}

对于std::initializer_list<>,该loop也适用,因为其有begin()以及end()成员。
即:

for(auto item : {1,2,3,4}){
        std::cout<<item<<std::endl;
}

另外,对于传统的c风格数组,该for loop 同样适用:

int array[] = {1,2,3,4,5};
int sum = 0;
for(int item : array){
    sum += item;
}

最后,温馨提示:注意隐式转换问题(explicit)。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值