What happens to an STL iterator after erasing it in VS, UNIX/Linux?

前端 未结 4 694
轻奢々
轻奢々 2020-12-05 21:35

Please consider the following scenario:


map(T,S*) & GetMap(); //Forward decleration

map(T, S*) T2pS = GetMap();

for(map(T, S*)::iterator it = T2pS.begin()         


        
4条回答
  •  心在旅途
    2020-12-05 21:58

    Yes, if you erase an iterator, that iterator gets a so-called singular value, which means it doesn't belong to any container anymore. You can't increment, decrement or read it out/write to it anymore. The correct way to do that loop is:

    for(map::iterator it = T2pS.begin(); it != T2pS.end(); T2pS.erase(it++)) {
        // wilhelmtell in the comments is right: no need to check for NULL. 
        // delete of a NULL pointer is a no-op.
        if(it->second != NULL) {
            delete it->second;
            it->second = NULL;
        }
    }
    

    For containers that could invalidate other iterators when you erase one iterator, erase returns the next valid iterator. Then you do it with

    it = T2pS.erase(it)
    

    That's how it works for std::vector and std::deque, but not for std::map or std::set.

提交回复
热议问题