C++11常用特性介绍——for循环新用法

一、for循环新用法——基于范围的for循环

  for(元素类型 元素对象 : 容器对象)

  {

    //遍历

  }

  1)遍历字符串

  std::string str = "hello world";

  for(auto ch : str)

  {

    std::cout << ch << std::endl;

  }

  2)遍历数组

  int arr[] = {1,2,3,4,5};

  for(auto i : arr)

  {

    std::cout << i << std::endl;

  }

  //不用知道数组容器的大小,即可方便的遍历数组。

  2)遍历stl容器

  vector<int> v = {1,2,3,4,5};

  for(atuo& i : v)

  {

    std::cout << i << std::endl;

  }

  //通过引用可以修改容器内容

  3)遍历stl map

  std::map<int,int> map = { {1,1},{2,2},{3,3} };

  for(auto i : map)

  {

    std::cout << i.first << i.second << std::endl;

  }

  遍历map返回的是pair变量,不是迭代器。

posted on 2019-11-14 11:58  zhangnianyong  阅读(598)  评论(0编辑  收藏  举报