Get error: vector iterator is incompatible

I am making a class program that runs a hotel. I can successfully register a client in the room. But when I try to check out a client from the room, I get a runtime error: The vector iterator is not compatible. I started the debugger and said the problem was in the expression of the condition of my while loop, but I can't figure out what the problem is (I think I was using the debugger correctly). I tried to look at another post with a similar error, but I couldn't find a solution. Can anyone please 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);
        }
    }
}

      

+3


source to share


3 answers


Iterators

std::vector

are invalid after the operation erase

. (see link 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;
       }
   }
}

      

+5


source


You are not promoting your iterator anywhere.

You need to do ++iter

at some point, or your while loop will endlessly.



Also don't forget what .erase

makes the iterator invalid, so you can't just advance after the erase. Do iter = roomsCheckedInto.erase(iter);

if the identifier matches.

+1


source


First, you need to increment something, or you never get to the end of roomsCheckedInto, meaning you have an infinite loop.

Second, erase invalidates the iter.

Instead, replace the while loop with the following:

while(iter != roomsCheckedInto.end())
{
   if(*iter==rID) iter = roomsCheckedInto.erase(iter);
   ++iter;
}

      

Also, is this homework? If yes, tag as such =)

0


source







All Articles