Common C ++ 11 features introduced new usage cycle --for

A, for a new cycle usage - based on the scope of the for loop

  for (element type element objects: container objects)

  {

    // iterate

  }

  1) traversal strings

  std::string str = "hello world";

  for(auto ch : str)

  {

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

  }

  2) through the array

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

  for(auto i : arr)

  {

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

  }

  // do not know the size of an array of containers, you can easily traverse the array.

  2) traverse the container stl

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

  for(atuo& i : v)

  {

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

  }

  // You can modify the contents of the container by reference

  3) traverse 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;

  }

  Traversing the map returns pair variable, not an iterator.

Guess you like

Origin www.cnblogs.com/zhangnianyong/p/11855572.html