Reputation: 415
Why does the following code produce an assertion error: Expression: list iterators incompatible
?
#include <list>
using namespace std;
int main()
{
list<int> a;
a.push_back(1);
list<int>::iterator iter=a.begin();
a.erase(iter);
iter==a.end();
}
Upvotes: 0
Views: 249
Reputation: 3759
the iterator is invalid after the erase. in your case erase itself returns (you drop it) the end iterator as you were deleting the last element
Upvotes: 0
Reputation: 153955
When erasing iter
it got invalidated. I think invalid iterator can't be used for anything other than assigning to them, not even comparing them with anything. You might have wanted to use
iter = a.end();
Upvotes: 0
Reputation: 5399
What you want to do is this:
#include <list>
using namespace std;
int main()
{
list<int> a;
a.push_back(1);
list<int>::iterator iter=a.begin();
iter = a.erase(iter);
}
Upvotes: 1
Reputation: 4302
An iterator on a given collection a
becomes invalid when a
changes, e.g. by removing an element.
Upvotes: 0