c++ - 为什么编译器会跳过 for 循环?

标签 c++ algorithm for-loop sum stdvector

我尝试用 vector 做一些练习,我做了一个简单的 for 循环来计算 vector 中元素的总和。该程序没有按我预期的方式运行,所以我尝试运行调试器,令我惊讶的是,不知何故,编译器完全跳过了 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-- 而不是计数++)

最佳答案

你的循环条件是错误的,因为它们总是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);分配一个整数 vector 并用0初始化秒。意思是,此行之后的循环(即在 main() 中)

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

将再向其中插入 10 个元素(即 i s),您最终将得到 myvector。与 20元素。你可能打算做

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

或更简单地使用 std::iota 来自 <numeric>标题。

#include <numeric> // std::iota

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

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

关于c++ - 为什么编译器会跳过 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58534404/

相关文章:

c++ - 在 map 初始化列表中使用 std::make_pair

python - 查找用简单的几何级数创建的树的祖先节点

python - 我的ee没有定义?我定义它。在这个 if 的 for 循环中

php - 在 PHP 中使用 Foreach 循环时邮件正文复制

if-statement - 使用批处理文件将多个 .csv 文件逐行合并为一个 .csv 文件

c++ - 为什么我没有正确解析?

c++ - 通过指针偏移访问结构变量值

c++ - 在 getter 中对嵌套 getter 结果进行扁平化的最佳方法

线性模式匹配算法?

algorithm - 8 拼图有多少种可能的状态?