简体   繁体   English

C ++迭代器的生命周期和有效性是什么?

[英]What is the lifetime and validity of C++ iterators?

I'm planning to implement a list of Things in C++ where elements might be removed out of order. 我打算在C ++中实现一个Things列表,其中的元素可能会被无序删除。 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. 所以我想到std::list<Thing*> with this->position = insert(lst.end(), thing)应该做的伎俩。 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. 我希望Thing类能够记住每个实例的位置,这样我以后就可以在恒定时间内轻松地执行lst.erase(this->position)

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. 但是,我对C ++ STL容器仍然有点新意,我不知道将迭代器保持这么长时间是否安全。 Especially, given that there will be other elements deleted ahead and after the inserted Thing before it's gone. 特别是,考虑到在插入Thing之前和之后将删除其他元素。

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*. 在你的情况下,即使在插入Thing *之前和之后删除了其他元素,保持迭代器也应该没问题。

EDIT : 编辑

Additional details for vector and deque: vector和deque的其他细节:

Vector : 矢量

  • inserting --- All iterators get invalid if reallocation happens, otherwise its valid. 插入---如果重新分配发生,所有迭代器都会失效,否则它是有效的。
  • erasing ---- All iterators after erase point get invalid. 擦除----擦除点后的所有迭代器都无效。

deque : deque

  • inserting --- All iterators get invalid. 插入---所有迭代器都无效。
  • erasing ---- All iterators get invalid. 擦除----所有迭代器都无效。

This depends on the container you use. 这取决于您使用的容器。

Check: http://www.sgi.com/tech/stl/ 检查: 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). 对于std :: list <>,它们在所有条件下都保持有效,直到它们实际引用的元素从容器中删除(此时它们无效)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM