繁体   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