C++中for循环的5种语法,你可知道?

来源:互联网 发布:三菱军刺淘宝上叫什么 编辑:程序博客网 时间:2024/06/01 21:25

在最新的C++中,支持for循环的5种用法,你可知道?

[cpp] view plain copy
 print?
  1. #include <algorithm>  
  2. #include <vector>  
  3. //////////////////////////////////////////////  
  4. int nArray[] = {0, 1, 2, 3, 4, 5};  
  5. std::vector<int> vecNum(nArray, nArray + 6);  
  6. CString strText;  
  7. // 第一种用法:最原始的语法(用下标)  
  8. for (size_t i = 0; i < vecNum.size(); ++i)  
  9. {  
  10.     strText.Format("%d", nArray[i]);  
  11.     AfxMessageBox(strText);  
  12. }  
  13.   
  14. // 第二种用法:最原始的语法(用迭代器)  
  15. for (auto it = vecNum.begin(); it != vecNum.end(); ++it)  
  16. {  
  17.     strText.Format("%d", *it);  
  18.     AfxMessageBox(strText);  
  19. }  
  20.   
  21. // 第三种用法:简化数组遍历语法(从vs2008开始支持)  
  22. for each(auto item in vecNum)  
  23. {  
  24.     strText.Format("%d", item);  
  25.     AfxMessageBox(strText);  
  26. }  
  27.   
  28. // 第四种用法:STL函数  
  29. std::for_each(vecNum.begin(), vecNum.end(), [](int item){  
  30.                                                    CString strText;  
  31.                                                strText.Format("%d", item);  
  32.                                        AfxMessageBox(strText);  
  33.                                                     });  
  34.   
  35. // 第五种用法:C++11新增加的(VS2012支持)  
  36. for(auto item : vecNum)  
  37. {  
  38.     strText.Format("%d", item);  
  39.     AfxMessageBox(strText);  
  40. }  


长见识了没有?在第四种用法中涉及到了Lambda表达式。

是不是越来越简化啦!


原创粉丝点击