C++ 迭代器的生命周期和有效性是多少?
我计划在 C++ 中实现一个事物列表,其中元素可能会被乱序删除.我不希望我需要任何形式的随机访问(我只需要定期扫描列表),并且项目的顺序也不重要.
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.
所以我想到了std::list<Thing*>使用 this->position = insert(lst.end(), thing)
应该可以解决问题.我希望 Thing 类记住每个实例的位置,以便我以后可以在恒定时间内轻松地执行 lst.erase(this->position)
.
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.
但是,我对 C++ STL 容器还是有点陌生??,我不知道将迭代器保留这么长时间是否安全.特别是考虑到在插入的 Thing 消失之前和之后会有其他元素被删除.
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.
推荐答案
在列表中,所有迭代器在插入过程中保持有效,只有擦除元素的迭代器在擦除过程中无效.
In list all iterators remain valid during inserting and only iterators to erased elements get invalid during erasing.
在您的情况下,即使在插入的 Thing* 前后删除其他元素时,保持迭代器也应该没问题.
In your case keeping iterator should be fine even when other elements deleted ahead and after the inserted Thing*.
编辑:
vector 和 deque 的更多细节:
Additional details for vector and deque:
向量:
- inserting --- 所有迭代器得到如果发生重新分配则无效,否则有效.
- 擦除----之后的所有迭代器擦除点无效.
双端队列:
- inserting --- 所有迭代器得到无效.
- 擦除 ---- 所有迭代器得到无效.
相关文章