C++中的新标准的for循环的应用

  1. 转自http://blog.csdn.net/qq_21400315/article/details/50561030
  2.   
  3. #include "stdafx.h"  
  4. #include <iostream>  
  5. #include<vector>  
  6. int _tmain(int argc, _TCHAR* argv[])  
  7. {  
  8.     int nums[3] = { 0, 1, 2 };  
  9.     std::vector<int>vs = { 0, 1, 2, 3, 4 };  
  10.     for (int num : nums)  
  11.     {  
  12.         std::cout << num << " ";  
  13.     }  
  14. ////这个应该是最常用的,for(int u:nums)
  15.     std::cout << std::endl;  
  16.     for (int v : vs)  
  17.     {  
  18.         std::cout << v<<" ";  
  19.     }  
  20.     std::cout << std::endl;  
  21. //这个也是可以用一下的
  22.     for each (int num  in nums)  
  23.     {  
  24.         std::cout << num << " ";  
  25.     }  
  26.     std::cout << std::endl;  
  27.     for each (int v  in vs)  
  28.     {  
  29.         std::cout << v << " ";  
  30.     }  
  31.     system("pause");      
  32.     return 0;  
  33. }  

如果你使用过c#或者java你肯定会对其中的foreach用法十分熟悉,因为在特定的循环操作中它实在是太方便了。其实在c++中也提供了类似的用法,在这里提供了两种用法,需要注意的是下面那个是c++ foreach用法,记住for和each是分开的。

原文地址:https://www.cnblogs.com/fenglongyu/p/7521517.html