Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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,

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading