Problem with std::map::iterator after calling erase()

后端 未结 5 767
無奈伤痛
無奈伤痛 2020-12-01 07:01
// erasing from map
#include 
#include 
using namespace std;

int main ()
{
  map mymap;
  map::iterator i         


        
5条回答
  •  情书的邮戳
    2020-12-01 07:24

    Erasing an element of a map invalidates iterators pointing to that element (after all that element has been deleted). You shouldn't reuse that iterator.

    Since C++11 erase() returns a new iterator pointing to the next element, which can be used to continue iterating:

    it = mymap.begin();
    while (it != mymap.end()) {
       if (something)
          it = mymap.erase(it);
       else
          it++;
    }
    

    Before C++11 you would have to manually advance the iterator to the next element before the deletion takes place, for example like this:

    mymap.erase(it++);
    

    This works because the post-increment side-effect of it++ happens before erase() deletes the element. Since this is maybe not immediately obvious, the C++11 variant above should be preferred.

提交回复
热议问题