[英]Why does the compiler skip the for-loop?
I have tried to do some practice with vector
, and I made a simple for
loop to calculate the sum of the elements within the vector.我尝试用vector
做一些练习,并且我做了一个简单for
循环来计算向量中元素的总和。 The program did not behave in the way I expect, so I try to run a debugger, and to my surprise, somehow, the compiler skips the for
loop altogether, and I have not come up with a reasonable explanation.该程序的行为与我预期的不一样,所以我尝试运行调试器,令我惊讶的是,编译器不知何故完全跳过了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;
}
I have done some research, and usually the ill-defined for
loop shows up when the final condition cannot be met (Ex: when setting count--
instead of count++
)我做了一些研究,通常当最终条件无法满足时会出现定义不明确for
循环(例如:设置count--
而不是count++
时)
Your loop's conditions are wrong, as they are always false
!您的循环条件是错误的,因为它们总是false
的!
Look at to the loops there看看那里的循环
for (int i = 0; i == 10; i++)
// ^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
and和
for (int count=0; count==4; count++)
// ^^^^^^^^^-----> condition : is it `true` when i is 0 (NO!!)
you are checking i
is equal to 10
and 4
respectively, before incrementing it.在增加 i 之前,您正在检查i
分别等于10
和4
。 That is always false
.那总是false
的。 Hence it has not executed further.因此它没有进一步执行。 They should be他们应该是
for (int i = 0; i < 10; i++)
and for (int count=0; count<4; count++)
for (int i = 0; i < 10; i++)
和for (int count=0; count<4; count++)
Secondly, vector<int> myvector(10);
其次, vector<int> myvector(10);
allocates a vector of integers and initialized with 0
s.分配一个整数向量并用0
初始化。 Meaning, the loop afterwards this line (ie in the main()
)意思是,这一行之后的循环(即在main()
中)
for (int i = 0; i == 10; i++) {
myvector.push_back(i);
}
will insert 10 more elements (ie i
s) to it, and you will end up with myvector
with 20
elements.将再插入 10 个元素(即i
s),你最终会得到带有20
元素的myvector
。 You probably meant to do你可能打算做
std::vector<int> myvector;
myvector.reserve(10) // reserve memory to avoid unwanted reallocations
for (int i = 0; i < 10; i++)
{
myvector.push_back(i);
}
or simpler using std::iota
from <numeric>
header.或更简单地使用来自<numeric>
header 的std::iota
。
#include <numeric> // std::iota
std::vector<int> myvector(10);
std::iota(myvector.begin(), myvector.end(), 0);
As a side note, avoid practising with using namespace std;
作为旁注, 避免练习using namespace std;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.