Reputation: 405
RemoveContact_HI have created this function to remove an element in a vector:
void JNP::IPComm_HostType::RemoveContact_H( UINT contactIndex,std::vector<IPContact>& l )
{
assert( contactIndex < l.size() );
l.erase( l.begin() + contactIndex );
}
However it does not appear to work. The element is not removed when I call the function. The size of the vector is reduced by 1, but you can still access all all the elements including the deleted element by coding
hostList[some integer]
I.e if hostList had 2 elements and I were to call
RemoveContact_H( 0, hostList )
the size would be reduced to 1, but both elements would still exits and could be accessed!
EDIT
Unsurprisingly, the error was due to my coding and not the vector::erase() function. I had previously defined the equals operator for the IPContact class which didn't actually copy any data.
Upvotes: 1
Views: 2564
Reputation: 14510
It is Undefined behavior to access elements already erased from a vector. Sometimes it will work (your case) but it will crash at the worst moment possible (i.e. during the demos, or in front of your family ;) ).
But if you use std::vector::at
to access the element already erased, it will throw a std::out_of_range
exception.
The std::vector::operator[]
does not perform a bounds checking.
the size would be reduced to 1, but both elements would still exits and could be accessed!
Like I said before, it is Undefined Behavior and you should not try to access erased elements. Try to do it with vector::at
, it will throw an exception.
Upvotes: 5
Reputation: 15069
the size would be reduced to 1, but both elements would still exits and could be accessed!
No. If your vector's size is 1 then only one element exists (index 0) and only this element can be accessed. Trying to access elements beyond that is Undefined Behaviour and as such it may crash your program or it may appear to work, who knows, but in the latter case that doesn't make your code any more correct.
In other words, std::vector::erase()
is behaving as it should, it's just that you're not using std::vector
as you should (ie. you must never try to access an element past the end).
You might want to use std::vector::at()
instead of std::vector::operator []()
in order to verify by yourself that only index 0 is accessible.
Upvotes: 3