为什么我的程序会跳过 while 循环? 2 大于 -1

Why does my program skip the while loop? 2 is bigger than -1

在测试程序中,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 << "!";
    }
}

当比较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){

      |