[英]vector.size() is working unexpectedly in comparision
When I use vector.size() in comparisions it gives unexpected results 当我在比较中使用vector.size()时,会产生意外的结果
vector<int> v;
for(int i = 0; i < v.size() -1;++i){
printf("i = %d\n", i);
printf("v[i] = %d\n", v[i]);
}
since the size of vector is 0, it shoudn't print anything but, it enters for loop and prints i = 0
and give segmentation fault. 由于向量的大小为0,因此它不打印任何内容,而是进入循环并打印i = 0
并给出分段错误。 But it shouldn't even enter the for loop as v.size() - 1
is -1
. 但是它甚至不应该进入for循环,因为v.size() - 1
为-1
。
Why is it happening? 为什么会这样呢?
The problem is your loop: 问题是您的循环:
for(int i = 0; i < v.size() -1;++i)
More specifically, this part of the condition: v.size() - 1
. 更具体地说,这部分条件是: v.size() - 1
。
The size
function returns a value of type size_type
, which if you read eg this vector
reference will see is an unsigned type. size
函数返回一个类型为size_type
的值,如果您阅读了此vector
引用,则该vector
将为无符号类型。
That means when you subtract 1
from the value 0
, you don't get -1
but instead get a very large value since unsigned underflow wraps around to its highest value. 这意味着当您从值0
减去1
时,您不会得到-1
,而是得到了一个非常大的值,因为无符号下溢会回绕到其最大值。
That means your loop will indeed iterate, at least once, and lead to UB (Undefined Behavior) when you index out of bounds. 这意味着您的循环确实会至少迭代一次,并且在超出范围时会导致UB(未定义行为)。
向量大小是一个无符号的整数,因此v.size()-1永远不会为-1,而是一些非常大的整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.