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

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

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

//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;
}

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

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

据我了解 id2 不应显示任何值。这样好还是我误解了 erase 的用法?如果是,显示后如何删除?

您正在从地图上擦除指针,但地图指向的对象并未被擦除。你需要花点时间学习一下c++的内存管理。

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

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

这将找不到任何东西

基本上你有未定义的行为调用

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

当与 dict.erase(it);.

一起使用时,迭代器变量不会以某种方式 reset

此外,在使用 erase() 之前,您应该注意调用 delete。否则你会泄漏内存。