迭代器相当于空指针?

发布于 2024-10-07 01:25:10 字数 288 浏览 0 评论 0原文

在我当前正在实现的算法中,我需要操作 struct T 的 std::list 。 T 持有对 T 的另一个实例的引用,但该引用也可以是“未分配的”。 起初,我想使用指针来保存此引用,但使用迭代器可以更轻松地从列表中删除。

我的问题是:如何用迭代器表示与空指针等效的内容?

我读到一般的解决方案是使用 myList.end() ,但就我而言,我需要测试迭代器是否为“null”,并且我可以在存储迭代器的时刻向列表添加或删除元素当我从列表中删除它时...我应该使迭代器指向包含“null”元素的已知列表吗?或者有更优雅的解决方案吗?

In an algorithm I'm currently implementing, I need to manipulate a std::list of struct T.
T holds a reference to another instance of T, but this reference can also be "unassigned".
At first, I wanted to use a pointer to hold this reference, but using an iterator instead makes it easier to remove from the list.

My question is : how to represent the equivalent to null pointer with my iterator?

I read general solution is to use myList.end(), but in my case, I need to test whether the iterator is "null" or not, and I may add or remove elements to the list between the moment when I store the iterator and the moment I remove it from list... Should I make the iterator point to a known list containing the "null" element? Or is there a more elegant solution?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

叶落知秋 2024-10-14 01:25:10

根据this(我强调):

与其他碱基序列相比
容器(向量和双端队列)、列表
是最高效的容器
插入到除
的开始或结束
序列,并且与这些不同,所有
先前获得的迭代器和
参考文献在之后仍然有效
插入并引用相同的内容
他们之前提到的元素。

这同样适用于擦除(明显的例外是引用已删除元素的迭代器变得无效)。所以是的,获取 end() 将始终指向相同的“无效”元素,并且应该可以安全使用。

According to this (emphasis by me):

Compared to the other base sequence
containers (vector and deque), lists
are the most efficient container doing
insertions at some position other than
the beginning or the end of the
sequence, and, unlike in these, all of
the previously obtained iterators and
references remain valid after the
insertion and refer to the same
elements they were referring before.

The same applies to erasure (with the obvious exception of iterators referring to a deleted element becoming invalidated). So yes, obtaining end() will always point to the same "invalid" element and should be safe to use.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文