std::forward_list -- 使用存储的迭代器擦除
std::forward_list -- erasing with a stored iterator
我正在尝试保留特定(基)类实例的全局列表,以便我可以随时通过遍历此全局列表来跟踪它们。
我相信解决这个问题的最正确方法是使用侵入性列表。例如,我听说可以通过深入研究Linux内核来遇到这些生物。
在我所处的情况下,我真的不需要这样的性能保证,使用侵入性列表会让我的事情变得有些复杂。
以下是到目前为止我实现这个知道其所有实例的类概念的内容。
class A {
static std::forward_list<A*> globallist;
std::forward_list<A*>::iterator listhandle;
public:
A() {
globallist.push_front(this);
listhandle = globallist.begin();
}
virtual ~A() {
globallist.erase_after(...); // problem
}
};
问题是没有forward_list::erase()
,而且看起来真的不像在 ctor 中保存globallist.before_begin()
对我有多大好处。我永远不应该取消引用before_begin()
的迭代器。它真的会保住这个位置吗?如果我保存before_begin
的迭代器,然后push_front()
一个新项目,该迭代器可能仍然无法取消引用,但它是否可以发送到erase_after()
?
forward_list
是一个单链表。要删除中间的节点,您必须以某种方式具有指向前一个节点的指针。例如,您可以执行以下操作:
class A {
static std::forward_list<A*> globallist;
std::forward_list<A*>::iterator prev_node;
public:
A() {
A* old_head = globallist.front();
globallist.push_front(this);
prev_node = globallist.before_begin();
old_head->prev_node = globallist.begin();
}
};
将第一个元素推送到空列表中的情况以及删除逻辑留给读者作为练习(删除时,将prev_node
复制到下一个节点的prev_node
)。
或者,只需使用std::list
并避免所有这些麻烦。
相关文章:
- 引用一个已擦除类型(void*)的指针
- 擦除while循环中迭代的元素
- 在运行时处理类型擦除的数据-如何不重新发明轮子
- C++擦除(如果存在)
- 在映射擦除c++期间执行循环的次数
- 为什么擦除方法会影响结束方法
- C++ 字符串类擦除成员函数的时空复杂性
- 类型擦除的std::function与虚拟函数调用的开销
- C++14 中unordered_map矢量和擦除删除成语的奇怪行为
- C++ 擦除函数中需要澄清
- 循环挂起迭代的 std::擦除 on std::list
- 擦除许多矢量元素,同时使用'auto'
- 如何擦除冗余输入?
- C++ STL 设置按值擦除
- 如何在C++中允许成员函数的自定义返回类型进行类型擦除?
- 为什么我的向量::擦除调用会抛出"vector subscript out of range"?
- 如何在写入文件时擦除最后一个逗号
- std::forward_list -- 使用存储的迭代器擦除
- 存储要擦除的矢量元素
- std::list 的擦除成员函数是否为所有存储的元素调用析构函数?