如何从C ++中的向量中删除节点 这段代码甚至没有编译
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;
}
行失败
local_container.erase(remove(local_container.begin(), local_container.end(), i), local_container.end());
编译器抱怨不平等分配。
答案 0 :(得分:3)
我认为你很难做到这一点。您可以使用带有lambda表达式的标准库中的std::remove_if
来代替手写循环来迭代容器。
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;
}
上述功能将删除符合条件的所有元素。如果您只想删除第一个匹配元素,那么这只是一个简单的更改。
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;
}