Search code examples
c++liststructerase

How to erase an object of a list containing pointers to a struct?


I have a struct called Node with 3 members, one of which acts as an id for the objects:

struct Node {
  string mem1;
  string mem2;
  int id;
}

And a list containing pointers to Node objects:

list<Node*> g_node;

The problem comes when trying to erase a specific object from that list (localized by the id). I have this code but doesn't work:

list<Node>::iterator it = g_node.begin();
            while (it != g_node.end()){
                if (it->id == iden)
                {
                    g_node->erase(it);
                }
            }
        } else if (iden != 0) {

"iden" is the id of an object to be deleted, and is input by the user.

What's going wrong?


Solution

  • remove_if is a great idea, but if you want to have a function that you can easily reuse and customize at your will, you can do it like this:

    bool remove_from_list(int id, list<Node*> &g_node)
    {
        auto it = g_node.begin();
    
        while (it != g_node.end())
        {
            if ((*it)->id == id)
            {
                // free memory... if you allocated those pointers
                delete (*it); 
                g_node.erase(it);
                return true;
            }
            else
                it++;
        }
    
        return false;
    }
    
    list<Node*> g_node;
    g_node.push_back(new Node { "a", "b", 5 });
    g_node.push_back(new Node { "ee", "77", 6 });
    remove_from_list(5, g_node);