Search code examples
c++dictionaryerase

C++ map::erase() does not erase data


I'm trying to test C++ map::erase() with the following code:

//file user.h
#include <string>
#include <fstream>
#include <cstring>

using namespace std;

class User {
    string name;
    int id;
public:
    User(const string& name, int id) : name(name), id(id) {}
    int getID() const {return id;}
    ~User(){}
};

//file main.cpp
#include "user.h"
using namespace std;

typedef map<string, User*> Dict;

int main()
{
    Dict dict;
    dict["Smith"] = new User("Smith", 666); //Id = 666
    dict["Adams"] = new User("Adams", 314); //Id = 314


    auto it = dict.find("Adams"); //look for user 'Adams'

    if (it == dict.end())         

    //show 'not Found' if didn't find 'Adams'
    cout << "not Found" << endl; 

    else
    //else, show the Id = 314
    cout << "id1: " << it->second->getID() << endl;


    //Here I think there is a problem
    //I ask to delete Adams from the list
    dict.erase(it);
    //So in this print the ID shouldn't be found
    cout << "id2: " << it->second->getID() << endl;

    return 0;
}

After I try to delete the item from the list it seems like it is not deleted as the program shows the following:

pc@pc:~/Test$ ./main
id1: 314
id2: 314

As I understand id2 shouldn't show any value. Is this good or did I misunderstood the use of erase. If yes, how can I delete the item after it is shown?


Solution

  • Basically you have undefined behavior calling

    dict.erase(it);
    //So in this print the ID shouldn't be found
    cout << "id2: " << it->second->getID() << endl;
    

    The iterator variable isn't somehow reset when it was used with dict.erase(it);.


    Also you should take care to call delete before using erase(). Otherwise you would leak memory.