Josh Wang
Josh Wang

Reputation: 415

STL iterator: Assertion Error

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

Answers (4)

stefan
stefan

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

Dietmar K&#252;hl
Dietmar K&#252;hl

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

cxxl
cxxl

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

kostrykin
kostrykin

Reputation: 4302

An iterator on a given collection a becomes invalid when a changes, e.g. by removing an element.

Upvotes: 0

Related Questions