从std::列表中删除项,并且只能访问迭代器

Remove item from std::list with only having access to the iterator

本文关键字:访问 迭代器 列表 std 删除      更新时间:2023-10-16

std::list是一个双链表。这难道不意味着只需访问迭代器就可以从列表中删除项目吗?

也许我的问题不够清楚。

#pragma once
#include <list>

typedef std::list<int> IntList ;
typedef IntList::iterator IntIterator;
class IntHiddenList
{
private:
    IntList list;
public:
    IntIterator AddInt(int x)
    {
        list.push_front(x);
        return list.begin();
    }
};
int main()
{
    IntHiddenList a;
    IntIterator it = a.AddInt(5);

    // How would I go about deleting 5 from the list using only "it"?
}

是的,理论上是可能的。然而,标准库不允许它(它需要容器和迭代器来擦除)。

不管你运气如何:boost提供boost::instrusive(http://www.boost.org/doc/libs/1_54_0/doc/html/intrusive/list.html)做你想做的事的能力。

否,您仍然需要列表才能删除元素。

在STL中,迭代器只保存指向数据的指针,并提供在容器中移动的操作。你可以在这里看到很好的表格描述。