简体   繁体   English

C ++:从对象指针向量中删除元素而不删除其指向的对象的正确方法是什么?

[英]C++: What is the proper way to remove elements from a vector of object pointers without deleting the object it points to?

What is the proper way to remove elements from a vector of object pointers without deleting the object it points to? 从对象指针向量中删除元素而不删除其指向的对象的正确方法是什么?

I am trying to selectively remove elements from my vector 我正在尝试有选择地从向量中删除元素

std::vector<Node*>openNodes;

without destroying any of the Node objects being pointed to. 而不破坏任何指向的Node对象。 (Those nodes are being used elsewhere.) (这些节点正在其他地方使用。)

I tried using < algorithm >'s remove_if function like so 我尝试像这样使用<算法>的remove_if函数

std::remove_if(openNodes.begin(),openNodes.end(),CheckClosedNode);

using my own custom comparator function 使用我自己的自定义比较器功能

bool CheckClosedNode(Node *tocheck)
{
    if(tocheck->isOpen)
        return false; //Don't remove. Node is still open.
    else
    {
        //std::cout << "node " << tocheck->id << " is being removed from open list..." << std::endl;
        return true; // Remove. Node is closed.
    }
}

However, when I std::cout the contents of openNodes, nothing has been removed. 但是,当我std :: cout openNodes的内容时,什么都没有删除。 I read that I ought to use std::erase() in conjunction with remove_if(), but erase() will delete the nodes. 我读到应该将std :: erase()与remove_if()结合使用,但是delete()将删除节点。 I thought of moving all elements that needed to be removed to the front of the vector and doing a pop_front(), but turns out that pop_front also deletes. 我想到将所有需要删除的元素移到向量的前面,并执行pop_front(),但事实证明pop_front也会删除。

Is there a standard way to remove elements from a vector without deleting the object? 是否有一种标准方法可以从向量中删除元素而不删除对象?

It actually won't delete the nodes if they are pointers. 实际上,如果它们是指针,则不会删除节点。 When you allocate memory for an object using new it is your job to delete the pointer. 使用new为对象分配内存时,删除指针是您的工作。 Now if you had declared it like vector<Node> this would be an issue since erase would have to call the deconstructor on Node. 现在,如果您像vector<Node>一样声明了它,这将是一个问题,因为擦除必须在Node上调用解构函数。 However a pointer is really like an int type (since it is just a memory address). 但是,指针实际上就像一个int类型(因为它只是一个内存地址)。 When you remove it from a vector nothing happens to the memory it points to. 当您从向量中删除它时,它所指向的内存没有任何反应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM