reference binding to null pointer of type 'value_type'
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.
The function, as posted, works fine for a vector whose elements are [1 1 2]
. See https://ideone.com/ppuRg5.
However, one problem I see in your function is that if you pass it an empty vector, it's going to run into problems.
while(i < nums.size() - 1)
will be a problem when nums
is empty. You can preemptively avoid that problem by returning from the function immediately if you find that it is an empty vector.
Also, use an unsigned type for i
to avoid compiler warnings about comparing signed and unsigned types.
int removeDuplicates(std::vector<int>& nums) {
if ( nums.empty() )
{
return 0;
}
unsigned int i = 0;
while(i < nums.size() - 1) {
if (nums[i] == nums[i + 1]) {
nums.erase(nums.begin() + i);
}
else i++;
}
return nums.size();
}