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;
}
我知道 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) << "\n";
}
输出:
false
这篇关于c ++向量大小。为什么-1大于零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!