为什么 std::vector::insert 在插入点之后使所有迭代器失效 [英] Why does std::vector::insert invalidate all iterators after the insertion point

查看:33
本文介绍了为什么 std::vector::insert 在插入点之后使所有迭代器失效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

insert-ing 到std::vector 时,C++ 标准确保插入点之前的所有迭代器只要容量 未耗尽(参见 [23.2.4.3/1] 或 std::vector 迭代器失效).

When insert-ing into a std::vector the C++ standard assures that all iterators before the insertion point remain valid as long as the capacity is not exhausted (see [23.2.4.3/1] or std::vector iterator invalidation).

不允许插入点后的迭代器保持有效(如果容量没有耗尽)背后的基本原理是什么?当然,它们随后会指向一个不同的元素,但是(从 std::vector 的假定实现来看)它应该仍然可以使用这样的迭代器(例如取消引用它或增加它).

What is the rationale behind not allowing iterators after the insertion point to remain valid (if the capacity is not exhausted)? Of course, they would then point to a different element but (from the presumed implementation of std::vector) it should still be possible to use such an iterator (for example dereference it or increment it).

推荐答案

迭代器可以引用不同的元素就足以使它们失效.迭代器应该在其有效生命周期内引用 same 元素.

That the iterators may refer to a different element is enough for them to be invalidated. An iterator is supposed to refer to the same element for the duration of its valid lifetime.

您是对的,在实践中,如果您取消引用这样的迭代器,您可能不会遇到任何崩溃或鼻恶魔,但这并不能使它有效.

You're right that, in practice, you may not experience any crashing or nasal demons if you were to dereference such an iterator, but that does not make it valid.

这篇关于为什么 std::vector::insert 在插入点之后使所有迭代器失效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆