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

c++ vector size. why -1 is greater than zero(c ++ 矢量大小.为什么 -1 大于零)
本文介绍了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 大于零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

OpenGL transforming objects with multiple rotations of Different axis(OpenGL 变换不同轴多次旋转的对象)
GLFW first responder error(GLFW 第一响应者错误)
SOIL not linking correctly(SOIL 连接不正确)
Core profile vs version string? Only getting GLSL 1.3/OGL 3.0 in mesa 10.0.1(核心配置文件与版本字符串?在 mesa 10.0.1 中只获得 GLSL 1.3/OGL 3.0)
What is the range of OpenGL texture ID?(OpenGL 纹理 ID 的范围是多少?)
How taxing are OpenGL glDrawElements() calls compared to basic logic code?(与基本逻辑代码相比,OpenGL glDrawElements() 调用的繁重程度如何?)