本文介绍了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容器有点新,我不知道如何保持迭代器这么长时间是安全的。

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.

在你的case保持迭代器应该很好,即使当其他元素前面删除和插入Thing *。

In your case keeping iterator should be fine even when other elements deleted ahead and after the inserted Thing*.

EDIT

vector和deque的其他详细信息:

Additional details for vector and deque:



  • 擦除----
    擦除点后的所有迭代器无效。

deque


  • - 所有迭代器获取
    无效。

  • erasing ----所有迭代器获取
    无效。

这篇关于C ++迭代器的生命周期和有效性是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 22:27