Reputation: 443
I'm having a problem deleting the last element of my list. It deletes the second to last element for some reason. There was a very useful post on this site about how to do it and it got me this far but I'm still having problems. I just don't quite understand how this doesn't work?
If I changed iter++
to ++iter
, I get an error trying to access invalid information when I delete the last element.
std::list<Recipe>::iterator iter = recipes.begin();
while(iter != recipes.end() )
{
if(iter->GetName() == buffer)
{
recipes.erase(iter++);
}
else
{
iter++;
}
}
Any help?
Upvotes: 0
Views: 2413
Reputation: 10719
when you call remove an iterator in c++ it will become invalid as an iterator, you should not do it this way..
You are right to use erase, but you should assign erase to the iter as erase returns an iterator to the the next element:
iter = recipes.erase(iter);
So this code should work:
while(iter != recipes.end() )
{
if(iter->GetName() == buffer)
{
iter = recipes.erase(iter);
}
else
{
iter++;
}
}
Now could very well be, that you equality is incorrect we do not know what buffer is or what GetName() returns, could you perhaps have two of those?
Upvotes: 4