为什么编译器会跳过 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 分别等于 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),你最终会得到 myvector20 元素。你可能打算做

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);

作为旁注,avoid practising with using namespace std;