I am making a program for class that manages a Hotel. I am able to successfully check-in a customer into a room. But when I try to check-out a customer from a room, I get a run-time error: vector iterator incompatible. I ran the debugger, and says the problem is in the condition statement of my while loop, but I cant figure out what the problem is (I think I used the debugger correctly). I tried looking at other post with this similar error but I was not able to find a solution. Can anyone help?
void Customer::removeRoomID(int rID)
{
vector<int>::iterator iter;
iter = roomsCheckedInto.begin();
while(iter != roomsCheckedInto.end()) // <--DEBUGGER SAYS ERROR IN THIS LINE - ERROR: VECTOR ITERATOR INCOMPATIBLE
{
if(*iter==rID)
{
roomsCheckedInto.erase(iter);
}
}
}
std::vector iterators are invalidated once an erase operation has been performed. (See reference here)
Try changing your code to:
void Customer::removeRoomID(int rID)
{
vector<int>::iterator iter;
iter = roomsCheckedInto.begin();
while(iter != roomsCheckedInto.end())
{
if(*iter==rID)
{
// iter should now be set to the value
// returned from the erase() method.
iter = roomsCheckedInto.erase(iter);
}
else
{
++iter;
}
}
}
You are not advancing your iterator anywhere.
You need to do ++iter at some point or your while loop will be endless.
Also don't forget .erase invalidates the iterator, so you can't simply advance after erase.
Do iter = roomsCheckedInto.erase(iter); in case of matching id.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With