C++ 的生命周期和有效性是多少? 迭代器?
我计划在 C++ 中实现一个事物列表,其中元素可能会被无序删除。 我不希望我需要任何类型的随机访问(我只需要定期扫描列表),并且项目的顺序也不重要。
所以我想到了 std::list
应该可以解决问题。 我希望 Thing 类记住每个实例的位置,以便以后可以在恒定时间内轻松执行 lst.erase(this->position)
。
然而,我对 C++ STL 容器还是有点陌生,我不知道保留迭代器这么长时间是否安全。 特别是,考虑到在插入的 Thing 消失之前,前面和后面还会有其他元素被删除。
I'm planning to implement a list of Things in C++ where elements might be removed out of order. I don't expect that i'll need any kind of random access (i just need to sweep the list periodically), and the order of items isn't important either.
So I thought of std::list<Thing*> with this->position = insert(lst.end(), thing)
should do the trick. I'd like the Thing class to remember the position of each instance so that i can later easily do lst.erase(this->position)
in constant time.
However, i'm still a bit new to C++ STL containers, and i don't know if it's safe to keep iterators for such a long time. Especially, given that there will be other elements deleted ahead and after the inserted Thing before it's gone.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在列表中,所有迭代器在插入期间保持有效,只有擦除元素的迭代器在擦除期间无效。
在您的情况下,即使其他元素在插入的 Thing* 之前和之后被删除,保留迭代器也应该没问题。
编辑:
向量和双端队列的其他详细信息:
向量:
如果发生重新分配则无效,
否则其有效。
擦除点无效。
deque:
无效的。
无效的。
In list all iterators remain valid during inserting and only iterators to erased elements get invalid during erasing.
In your case keeping iterator should be fine even when other elements deleted ahead and after the inserted Thing*.
EDIT:
Additional details for vector and deque:
Vector:
invalid if reallocation happens,
otherwise its valid.
erase point get invalid.
deque:
invalid.
invalid.
这取决于您使用的容器。
检查:http://www.sgi.com/tech/stl/
查看最后的每个容器文档,它们将描述迭代器保持有效的条件。
对于 std::list<> 它们在所有条件下都保持有效,直到它们实际引用的元素从容器中删除(此时它们无效)。
This depends on the container you use.
Check: http://www.sgi.com/tech/stl/
Look at each containers documentation at the end their will be a description on the conditions that iterators stay valid under.
For std::list<> they remain valid under all conditions until the element they actually refer to is removed from the container (at this point they are invalid).