Erasing elements in a multimap while iterating

后端 未结 2 1747
醉梦人生
醉梦人生 2020-12-31 09:26

I\'m writing a nodal path finding algorithm. I need to run through a multimap and delete elements out of it under certain conditions, but keep iterating through the multimap

相关标签:
2条回答
  • 2020-12-31 09:40

    Is it safe to erase the iterator pointer from the table before incrementing the iterator?

    No, erase will invalidate the iterator and you shouldn't increment it after that.

    To do this properly, make use of the return value of erase - the iterator following the last removed element:

    std::multimap<int, int> m;
    
    for (auto it = m.begin(); it != m.end(); ) {
       if (condition)
           it = m.erase(it);
       else
           ++it;
    }
    

    In C++03, erase returns nothing, so you have to do this manualy by saving a copy of the iterator and incrementing it before you erase the original:

    std::multimap<int, int> m;
    typedef std::multimap<int, int>::iterator Iter;¸
    
    for (Iter it = m.begin(); it != m.end(); ) {
       if ( /* some condition */ ) {
           Iter save = it;
           ++save;
           m.erase(it);
           it = save;
       } else
           ++it;
    }
    
    0 讨论(0)
  • 2020-12-31 10:04

    Won't this be better?

    std::multimap<int, int> m;
    typedef std::multimap<int, int>::iterator Iter;¸
    
    for (Iter it = m.begin(); it != m.end(); ) {
        if ( /* some condition */ ) {
            Iter save = it;
            ++it;
            m.erase(save);
        } else
           ++it;
    }
    
    0 讨论(0)
提交回复
热议问题