入口条件循环(1)

1:入口条件循环:先判断条件,若条件为true,则执行循环,反之结束;有for和whlie两种形式。

2:我们以菲波那契数列为例:在进行运算时,由于数字要相加,因此运算量较大。
在这里我们引入循环的概念:例如以下是五种for的循环。

#include <algorithm> 
 #include <vector> 
  int nArray[] = {0, 1, 2, 3, 4, 5};
    std::vector<int> vecNum(nArray, nArray + 6);
      CString strText;  
第一种用法:最原始的语法(用下标)  

   

 for (size_t i = 0; i < vecNum.size();  ++i)  
    {     
     strText.Format("%d", nArray[i]);    
      AfxMessageBox(strText); 
      }    
   



第二种用法:最原始的语法(用迭代器)  
for (auto it = vecNum.begin(); it != vecNum.end(); ++it) 
 {    
   strText.Format("%d", *it);   
   AfxMessageBox(strText);
  }  

   



第三种用法:简化数组遍历语法(从vs2008开始支持) 
     for each(auto item in vecNum) 
      {    
        strText.Format("%d", item); 
        AfxMessageBox(strText); 
       }  


第四种用法:STL函数  
         std::for_each(vecNum.begin(), vecNum.end(), 【】(int  item)({                                              
                         CString strText;                                                  
                         strText.Format("%d", item);                                        
                  AfxMessageBox(strText);                                                     
                   });    
第五种用法:C++11新增加的(VS2012支持) 
 for(auto item : vecNum) 
          {    
            strText.Format("%d", item);   
               AfxMessageBox(strText); 
           } 

从本质上来说,for循环是一种工具,用来重复运算和进行决策,for循环的组成部分。
1:设置初始值:比如这里设置了数组,array的数组有几个数字
2:进行测试,看循环是否继续进行。
3:执行循环操作。
4:更新用于测试的值。

控制部分:由初始化,测试,更新操作构成。如

for(auto item:vecNum)

控制部分后面是循环体。
注意事项:for是判断for循环的关键字,为防止编译器将for视为函数,for后面常用留下一个空格

for (i=6,i<10;i++)//判断部分后面用分号表示。
   smart-function(i);

/

猜你喜欢

转载自blog.csdn.net/weixin_43360397/article/details/84777796
今日推荐