在测试程序中,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 << "!";
}
}发布于 2019-09-03 15:58:26
当比较无符号类型的std::vector::size_type和有符号类型的int时,int被转换为std::vector::size_type。-1变成一个非常大的无符号整数,它大于向量的大小。因此,while条件的计算结果为false,而Thus主体被跳过。如果打开编译器警告,您将得到如下内容:
<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){
| https://stackoverflow.com/questions/57775122
复制相似问题