Howo
Howo

Reputation: 99

erase an element in vector by the iterator invalid, but it DOESN'T crash

int main()
{
    vector<int> v;
    v.reserve(10);
    for(int i=0;i<10;i++)
        v.push_back(i);

    for(vector<int>::const_iterator iter=v.begin();iter!=v.end();iter++) {
        if(*iter==5)
            v.erase(iter);
    }

    for(vector<int>::const_iterator iter=v.begin();iter!=v.end();iter++)
        cout<<*iter<<endl;

    return 0;
}

I'm sure the iter is .It should be like the following, or it will crash.

for(vector<int>::const_iterator iter=v.begin();iter!=v.end();) {
    if(*iter==5)
       iter=v.erase(iter);
    else
        iter++;
}

However, when I run the first program, it outputs:0,1,2,3,4,6,7,8,9. I read the C++ primer again and again,and googled it, felt confused still.

Upvotes: 2

Views: 96

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

From erase:

Invalidates iterators and references at or after the point of the erase, including the end() iterator.

Basically, it means, that the first code snippet is Undefined Behaviour.

And, as it is Undefined Behaviour, anything might happen (a crash is not required, the program might behave as you expected up to some moment in the future when it will suddenly crash).

Upvotes: 3

Related Questions