vector<T>::size()
returns a value of type size_t
, which is an unsigned type. Let’s say the vector passed in is empty and therefore the vector’s length is 0. nums.size() - 1
will cause integer underflow and you will actually be comparing 0
with a very large positive number. This will evaluate to true causing the loop to run and i
going pass the array bounds.
To fix this you can cast nums.size()
to int
preemptively or store the size in an integer variable and compare with that.