Search code examples
c++iteratorstdmap

crash for C++ map when deleting via iterator


I have the following code which crashes

#include <map>
#include <iostream>

using namespace std;

int main()
{
        map<int,int> m;
        m[1]=2;
        m[2]=3;
        m[3]=4;
        m[4]=5;
        /*
        m.insert(std::make_pair(1,2));
        m.insert(std::make_pair(2,3));
        m.insert(std::make_pair(3,4));
        m.insert(std::make_pair(4,5));
        */
        for (auto it=m.begin();it!=m.end();)
        {
                cout << it->first << "->" << it->second << endl;
                if (it->first == 3) {
                        auto next = ++it; // <------------------------
                        m.erase(it);
                        cout << "Restart " << endl;
                        it = m.begin();
                }
                else
                {
                        ++it;
                }
        }

        return 0;
}

The problem dissapears if I comment the line with <------------------ and I cannot explain myself why.

Any clues?


Solution

  • Your map is this (showing the keys only)

    { 1, 2, 3, 4 }
    

    You then loop through, find the 3, and erase the next element. Leaving this

    { 1, 2, 3 }
    

    Now you start from the beginning again, find the same three again and delete the next element, but this time there is no next element. Therefore you get a crash,