C++ map::erase() 不擦除数据

Mar*_*rco 3 c++ dictionary erase

我正在尝试map::erase()使用以下代码测试 C++ :

//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;
}
Run Code Online (Sandbox Code Playgroud)

在我尝试从列表中删除项目后,它似乎没有被删除,因为程序显示如下:

pc@pc:~/Test$ ./main
id1: 314
id2: 314
Run Code Online (Sandbox Code Playgroud)

据我了解,id2不应显示任何价值。这是好的还是我误解了erase. 如果是,我如何在显示后删除该项目?

pm1*_*100 5

您处于未定义行为领域。修改地图后,您正在使用迭代器 (it)。任何事情都可能发生 - 包括显然有效(有点)。你应该重做

auto it = dict.find("Adams"); //look for user 'Adams'
Run Code Online (Sandbox Code Playgroud)

这不会找到任何东西