Reputation: 9479
How do I remove a node from a vector in C++ This code does not even compile
typedef vector<simple_node> container;
//======================================
// remove an item from the queue that matches what we arelady have
container parser::removeFromQueue(container local_container, simple_node *node_to_remove)
{
for (auto i = local_container.begin(); i != local_container.end(); i++)
{
if ((i->toy == node_to_remove->toy) &&
(i->type == node_to_remove->type))
{
local_container.erase(remove(local_container.begin(), local_container.end(), i), local_container.end());
break;
}
}
return local_container;
}
It fails on the line
local_container.erase(remove(local_container.begin(), local_container.end(), i), local_container.end());
The compiler complains about an inquality assignment.
Upvotes: 1
Views: 162
Reputation: 18652
I think you're doing this the hard way. Instead of a hand-written loop to iterate over the container you can use std::remove_if
from the standard library with a lambda expression.
container parser::removeFromQueue(container local_container, simple_node *node_to_remove)
{
auto pred = [node_to_remove](const simple_node &node) {
return node.toy == node_to_remove->toy && node.type == node_to_remove->type;
};
local_container.erase(std::remove_if(local_container.begin(), local_container.end(), pred), local_container.end());
return local_container;
}
The above function will remove all elements that meet the condition. If you only want to remove the first matching element it's a simple change.
container parser::removeFromQueue(container local_container, simple_node *node_to_remove)
{
auto pred = [node_to_remove](const simple_node &node) {
return node.toy == node_to_remove->toy && node.type == node_to_remove->type;
};
auto itr = std::find_if(local_container.begin(), local_container.end(), pred);
if (itr != local_container.end()) {
local_container.erase(itr);
}
return local_container;
}
Upvotes: 3