【问题标题】:Remove a given item from a boost::intrusive::list从 boost::intrusive::list 中删除给定项目
【发布时间】:2017-05-18 18:54:52
【问题描述】:

我有一个指向保证在 boost::intrusive::list 中的对象的指针。鉴于该指针/对象,我可以将其从列表中删除吗?

以下说明了我正在尝试做的事情:

#include <boost/intrusive/list.hpp>

struct MyStruct : public boost::intrusive::list_base_hook<>  {
    int i;
    MyStruct(const MyStruct &) = delete;
    MyStruct& operator= (const MyStruct &) = delete;
    MyStruct(int val) : i(val) {}
};

void test()
{
    boost::intrusive::list<MyStruct> l;
    MyStruct a(1);

    l.push_back(a);

    MyStruct* p = &a;
    //At this point I have a pointer to an item that is in the list,
    //Given this pointer, is there any way I can remove that item from the list ? 
}

【问题讨论】:

  • “这失败了,好像 remove() 会按值删除项目” 你给了它一个值。 *p 不是指针。这是被指向的东西。当你像这样写你的声明时,它就不那么令人困惑了:MyStruct* p = &amp;a;
  • 我只是想删除我链接到侵入列表中的节点,你有这样做的方法吗?由于该项目没有被复制到列表中,因此考虑到添加到列表中的原始节点,当然应该可以将其删除。
  • 看起来它需要一个谓词,您可以轻松创建它boost.org/doc/libs/1_35_0/doc/html/intrusive/…
  • 这似乎是一个 O(n) 操作,当我手头已经有要删除的项目时,这是不可取的。如果答案是真的不可能,那我也可以。

标签: c++ boost


【解决方案1】:

你可以这样删除它:

l.erase(boost::intrusive::list<MyStruct>::s_iterator_to(*p));

注意它并没有被销毁,它只是从列表中删除。

此外,如果您使用带有自动取消链接选项的钩子,那么您可以简单地删除它:

p->unlink();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多