簡體   English   中英

為什么編譯器會跳過 for 循環?

[英]Why does the compiler skip the for-loop?

我嘗試用vector做一些練習,並且我做了一個簡單for循環來計算向量中元素的總和。 該程序的行為與我預期的不一樣,所以我嘗試運行調試器,令我驚訝的是,編譯器不知何故完全跳過了for循環,我還沒有提出合理的解釋。

//all code is written in cpp
#include <vector>
#include <iostream>
using namespace std;

int simplefunction(vector<int>vect)
{
   int size = vect.size();
   int sum = 0;
   for (int count = 0; count == 4; count++) //<<--this for loop is being skipped when I count==4
   {            
      sum = sum + vect[count];
   }
   return sum;  //<<---the return sum is 0 
}

int main()
{
   vector<int>myvector(10);
   for (int i = 0; i == 10; i++)
   {
      myvector.push_back(i);
   }
   int sum = simplefunction(myvector);
   cout << "the result of the sum is " << sum;    
   return 0;

}

我做了一些研究,通常當最終條件無法滿足時會出現定義不明確for循環(例如:設置count--而不是count++時)

您的循環條件是錯誤的,因為它們總是false的!

看看那里的循環

for (int i = 0; i == 10; i++) 
//              ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)

for (int count=0; count==4; count++)
//                ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)

在增加 i 之前,您正在檢查i分別等於104 那總是false的。 因此它沒有進一步執行。 他們應該是

for (int i = 0; i < 10; i++)for (int count=0; count<4; count++)


其次, vector<int> myvector(10); 分配一個整數向量並用0初始化。 意思是,這一行之后的循環(即在main()中)

for (int i = 0; i == 10; i++) {
    myvector.push_back(i);
}

將再插入 10 個元素(即i s),你最終會得到帶有20元素的myvector 你可能打算做

std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++) 
{
    myvector.push_back(i);
}

或更簡單地使用來自<numeric> header 的std::iota

#include <numeric> // std::iota

std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);

作為旁注, 避免練習using namespace std;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM