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

What is the lifetime and validity of C++ iterators?(C++ 迭代器的生命周期和有效性是多少?)
本文介绍了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 --- 所有迭代器得到无效.
  • 擦除 ---- 所有迭代器得到无效.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

C++ constant reference lifetime (container adaptor)(C++ 常量引用生命周期(容器适配器))
What is the lifetime of a CWnd obtained from CWnd::FromHandle?(从 CWnd::FromHandle 获得的 CWnd 的生命周期是多少?)
How is its lifetime of a return value extended to the scope of the calling function when it is bound to a const reference in the calling function?(当它绑定到调用函数中的 const 引用时,它的返回值的生命周期如何扩展到调用函数的范围?)
What is the lifetime of a C++ lambda expression?(C++ lambda 表达式的生命周期是多少?)
Lifetime of lambda objects in relation to function pointer conversion(与函数指针转换相关的 lambda 对象的生命周期)
const reference to a temporary object becomes broken after function scope (life time)(在函数作用域(生命周期)之后,对临时对象的 const 引用被破坏)