c ++ 矢量大小.为什么 -1 大于零

2021-12-21 00:00:00 comparison vector unsigned c++

请看一下这个简单的程序:

Please take a look at this simple program:

#include <iostream>
#include <vector>

using namespace std;

int main() {

vector<int> a;

std::cout << "vector size " << a.size() << std::endl;

int b = -1;

if (b < a.size())
   std::cout << "Less";
else
   std::cout << "Greater";

    return 0;
}

尽管 -1 明显小于 0,但它输出更大"这一事实让我感到困惑.我知道 size 方法返回无符号值,但比较仍然适用于 -1和 0. 那么发生了什么?谁能解释一下?

I'm confused by the fact that it outputs "Greater" despite it's obvious that -1 is less than 0. I understand that size method returns unsigned value but comparison is still applied to -1 and 0. So what's going on? can anyone explain this?

推荐答案

因为向量的大小是无符号整数类型.您正在将无符号类型与有符号类型进行比较,并且将二进制补码负有符号整数提升为无符号类型.这对应于一个大的无符号值.

Because the size of a vector is an unsigned integral type. You are comparing an unsigned type with a signed one, and the two's complement negative signed integer is being promoted to unsigned. That corresponds to a large unsigned value.

此代码示例显示了您所看到的相同行为:

This code sample shows the same behaviour that you are seeing:

#include <iostream>
int main()
{
  std::cout << std::boolalpha;
  unsigned int a = 0;
  int b = -1;
  std::cout << (b < a) << "
"; 
}

输出:

相关文章