使用 vector::size() 时,While 循环表现得很奇怪

问题描述 投票:0回答:1

我正在编写一段代码,该代码应该将向量增长到一定的大小。由于某种原因,while 循环中的布尔检查表现得很奇怪。

这是我运行的代码;第一个循环没有按预期运行,但第二个循环却运行了。据我所知,他们都应该做完全相同的事情。发生什么事了?

#include <iostream>
#include <vector>
using std::cout;
using std::vector;

int main()
{
  int index = 0;
  vector<int> vec = {};

  
  //Loop 1
  while (index > (vec.size() - 2))
  {
    cout << "Visiting loop 1\n";
    vec.push_back(vec.size());
  }

  bool test = (index > (vec.size() - 2));
  //I added this here because I noticed that it is initializing
  //as false, even though 0 > -2 is true. In fact,
  //when I type "p index > (vec.size() - 2)" in the debugger,
  //it says true, but when I type "p test", it says false. Why?

  vec = {};

  //Loop 2
  int compValue = vec.size() - 2;
  
  while (index > compValue)
  {
    cout << "Visiting loop 2\n";
    vec.push_back(vec.size());
    compValue = vec.size() - 2;
  }

  return 0;
}
c++ while-loop
1个回答
0
投票

每次 while 循环返回到条件时,您都会计算向量大小:

 while (index > (vec.size() - 2))

因此,当 while 块内的大小被修改时,当 while 循环再次评估条件时,您将获得不同的大小。

在第二个循环中,大小是一个常量,当您返回到 while 条件时,它不会被修改,因为您将其声明为常量:

int compValue = vec.size() - 2;

即使在 while 块内修改了向量大小 get,当循环返回到其条件时 comValue 仍然相同。

我希望这是有道理的。 还有 Tim Roberts 所说的,要小心无符号类型。

© www.soinside.com 2019 - 2024. All rights reserved.