euskadi
euskadi

Reputation: 127

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?

Upvotes: 1

Views: 99

Answers (2)

Ami Tavory
Ami Tavory

Reputation: 76297

Why not use std::list::remove_if?

g_node.remove_if([iden](const Node *n){return n->id == iden;});

Note that this will not delete the Node object (neither does your original code). With containers holding pointers, you might want to consider smart pointers.

Upvotes: 4

Jts
Jts

Reputation: 3527

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);

Upvotes: 1

Related Questions