nums is a vector, and I have one code line that
while(i < nums.size()-2 && nums[i] == nums[i+1]) i++;
It would give me a Runtime error, If I run the code when the nums.size() is 1. But if I change this line to:
while(i-2 < nums.size() && nums[i] == nums[i+1]) i++;
The build succeeds.
I have no idea, what is the difference in executing these two code line, and why does the build behave differently?
Does anyone has any idea? Thank you in advance.
std::vector<>.size()
returns an unsigned long
which, when combined with nums.size() - 2
gives an underflow and the result is some really big number which doesn't fit your code logic. Since the expression i < nums.size() - 2
will always evaluate to true
because of the underflow, you will keep iterating through the vector until you reach index greater than it's size, which will cause runtime error, more specifically vector index out of range
.