【问题标题】:Why does my program skip the while loop? 2 is bigger than -1 [duplicate]为什么我的程序会跳过 while 循环? 2大于-1 [重复]
【发布时间】:2019-09-04 00:04:55
【问题描述】:

在测试程序中,v的大小为2。由于2大于-1,我认为应该进入while循环和“!”应该无限打印。但是,while 循环被跳过。这是为什么?我在 VS 2017 和 Ideone 中测试了代码。

#include <iostream>
#include <vector>
int main(){
    std::vector<std::pair<int,float>> v = {{1,2.0},{2,2.0}};
    std::cout << v.size();
    while(v.size() > -1){
        std::cout << "!";
    }
}

【问题讨论】:

标签: c++ visual-studio-2017


【解决方案1】:

当比较std::vector::size_type 的无符号类型和int 的有符号类型时,int 被转换为std::vector::size_type-1 变成一个非常大的无符号整数,大于向量的大小。因此,while 条件的计算结果为false,而 while 正文被跳过。如果你打开compiler warnings,你会得到类似的东西:

<source>:6:20: error: comparison of integer expressions of different signedness: 'std::vector<std::pair<int, float> >::size_type' {aka 'long unsigned int'} and 'int' [-Werror=sign-compare]

    6 |     while(v.size() > -1){

      | 

【讨论】:

  • 注意:大多数编译器应该警告你(或任何人)这样的事情。
  • 抱歉,我一定是第一次错过了。我更多是为了 OP 的利益而提到它,而不是你,但你已经提到了它,我错过了它。所以请忽略我的评论。
猜你喜欢
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-01
  • 2012-11-07
  • 2019-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多