C++11 学习笔记 基于范围的for循环

一.  基于范围的for循环简介

在C++03/98中,不同的容器和数组,遍历的方法不尽相同,写法不统一,也不够简洁,而C++11基于范围的for循环以统一,简洁的方式来遍历容器和数组,用起来更方便了。

数组循环:

 using namespace std;
 
 const int size = 5;
 int* p = new int[size]{1,2,3,4,5};
 for(int i =0;i<size;i++){
     cout<<p[i]<<" ";
 }

容器循环:

 using namespace std;
 
 vector<int> vec;
 for (auto it=vec.begin(),it!=vec.end();it++){
     cout<<*it<<" ";
 }


当然,<algorithm>中还有一个for_each算法可以用来对容器进行遍历

  Function for_each( InputIterator begin, InputIterator end, Function f ) {
    while ( begin != end )
         f( *begin++ );
 }

 using namespace std;
 
 void do_cout(int& num){
     cout<<num<<" ";
 }
 
 vector<int> vec;
 for_each(vec.begin(),vec.end(),do_cout);

for_each

优点:不再需要关注迭代器(Iterator)的概念

缺点:必须显示的给出容器的开头(Begin)和结尾(End) 

 

在C++11中终于有基于范围的for循环(The range-based for statement)。

 #include <iostream>
 #include <vector>
 
 using namespace std;
 
 int main(){
     vector<int> arr = {1, 2, 3};
     for(auto n : arr){
         cout << n << endl;
     }
 
     return 0;
 }


在上面的基于范围的for循环中,在n的定义之后,紧跟一

  • 6
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值