是否有可能插入和/或删除元素会使现有元素的迭代器无效。
谢谢。
最佳答案
是的。 documentation对于 boost::ptr_vector<T>
状态:
A
ptr_vector<T>
is a pointer container that uses an underlyingstd::vector<void*>
to store the pointers.
并在 std::vector
中插入元素或从中删除元素可能会导致重新分配,从而使现有的迭代器失效。
具体来说,C++11 的 §23.3.6.5/3 说明了 erase()
:
(3) Effects: Invalidates iterators and references at or after the point of the erase.
关于insert()
和 push_back()
:
(1) Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.
因此,为了防止元素插入时迭代器失效,你可以使用reserve()
函数在从 vector 中获取任何迭代器之前增加 vector 的容量。这些迭代器将保持有效,直到 size()
。 vector 的数量超过了为元素空间预留的数量。
关于c++ - 当 ptr_vector 迭代器失效时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15050632/