简体   繁体   English

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

[英]c++ vector size. why -1 is greater than zero

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;
}

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?我对它输出“更大”的事实感到困惑,尽管 -1 显然小于 0。我知道size方法返回无符号值,但比较仍然适用于 -1 和 0。那么发生了什么? 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) << "\n"; 
}

output:输出:

false错误的

The signature for vector::size() is: vector::size()的签名是:

size_type size() const noexcept;

size_type is an unsigned integral type. size_type无符号整数类型。 When comparing an unsigned and a signed integer, the signed one is promoted to unsigned.当比较一个无符号和一个有符号整数时,有符号整数被提升为无符号整数。 Here, -1 is negative so it rolls over, effectively yielding the maximal representable value of the size_type type.这里, -1是负数,所以它会翻转,有效地产生size_type类型的最大可表示值。 Hence it will compare as greater than zero.因此它将比较为大于零。

-1 unsigned is a higher value than zero because the high bit is set to indicate that it's negative but unsigned comparison uses this bit to expand the range of representable numbers so it's no longer used as a sign bit. -1 unsigned 是比零更高的值,因为高位设置为表示它是负数,但无符号比较使用此位来扩展可表示数字的范围,因此它不再用作符号位。 The comparison is done as (unsigned int)-1 < 0 which is false.比较以(unsigned int)-1 < 0 ,这是错误的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM