Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase using iterator on C++ map

I am experiencing the following behavior: I create a map, do a find on the key and delete the map entry. After erase, I print the elements using the iterator and I expected it to dump core but it works.

Why does it work?

     typedef std::pair<std::string, int> pair;
    std::map<pair, int> nameidCntMap;

    pair pair1("ABC", 139812);
    pair pair2("XYZ", 139915);
    pair pair3("PQR", 139098);


    nameidCntMap.insert(std::make_pair(pair1, 1));
    nameidCntMap.insert(std::make_pair(pair2, 1));
    nameidCntMap.insert(std::make_pair(pair3, 1));

    std::map<pair, int>::iterator it = nameidCntMap.find(pair1);
    if (it != nameidCntMap.end())
    {
            symsrcidCntMap.erase(it);
   
            std::cout<<"Pair::first: "<<it->first.first << "Pair::second: "<<it->first.second<<"map second:"<<it->second<<std::endl;
    }
like image 455
Winjun Avatar asked Nov 30 '25 06:11

Winjun


1 Answers

Why does it work?

It doesn't "work".

Behaviour of the program is undefined.

expected it to dump core

Your expectation is misguided. The program isn't defined to "dump core" when you indirect through an invalid iterator. No behaviour is defined for such program. As such, any behaviour is possible. Among all possible behaviours, there is the possibility that the behaviour is what you didn't expect, or what you consider to be "working".

like image 149
eerorika Avatar answered Dec 01 '25 19:12

eerorika



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!