迭代器相当于空指针?
在我当前正在实现的算法中,我需要操作 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据this(我强调):
这同样适用于擦除(明显的例外是引用已删除元素的迭代器变得无效)。所以是的,获取
end()
将始终指向相同的“无效”元素,并且应该可以安全使用。According to this (emphasis by me):
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.