简体   繁体   中英

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM