gpt4 book ai didi

c++ - 迭代器等价于空指针?

转载 作者:IT老高 更新时间:2023-10-28 22:59:02 26 4
gpt4 key购买 nike

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

我的问题是:如何用我的迭代器来表示空指针的等价物?

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

最佳答案

根据this (我强调):

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.

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

关于c++ - 迭代器等价于空指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4419503/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com