基于范围的for循环

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;

}

原文地址:https://www.cnblogs.com/djcsch2001/p/15395009.html