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

时间:2023-05-08
本文介绍了c ++ 矢量大小.为什么 -1 大于零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

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

输出:

这篇关于c ++ 矢量大小.为什么 -1 大于零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:将文件读入 std::vector<char> 的有效方法? 下一篇:C++ 按值而不是按位置擦除向量元素?

相关文章