孤独的猫

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

for循环的新用法

我们知道,在C++中遍历一个容器的方法一般是这样的:

#include <iostream>

#include <vector>

 

int main(void)

{

  std::vector<int> arr;

  //...

  for(auto it=arr.begin();it !=arr.end();++it)

  {

    std::cout<<*it<<std::endl;

  }

  return 0;

}

 

上面借助前面介绍过的auto关键字,省略了迭代器的声明。

在C++11的标准中,可以用基于范围的for循环来书写了:

#include <iostream>

#include <vector>

 

int main(void)

{

  std::vector<int> arr;

  //...

  for(auto n:arr)

  {

    std::cout<<n<<std::endl;

  }

  return 0;

}

posted on 2021-10-11 21:07  孤独的猫  阅读(60)  评论(0编辑  收藏  举报