简体   繁体   中英

How many times a loop is executed during map erase c++

void main() {
        map<int, int> m;
        m[1] = 1;
        m[2] = 1;
        for (auto it : m) {
            cout<<"current: "<<it.first<<endl;
            m.erase(1);
            m.erase(2);
        }
    }

Guess how many times this loop is executed? It is 2!

However, if I remove "m.erase(1)", the loop is executed once.

I am confused on why the loop is executed twice?

std::map::erase will invalidate the iterator to the erased element. After which, the invalid iterator is used for increment operation in for range loop, which invokes an undefined behavior. So you can't basically tell the number of times it executes the loop.

The correct snippet would like like following:

for(auto it = m.begin(); it != m.end(); )
        if( /*condition */ )
            it = m.erase(it);
        else
            ++it;

I am confused on why the loop is executed twice?

The erase operation within the loop invalidates the iterators used in the loop. The behaviour of using invalidated iterators is undefined.

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