gpt4 book ai didi

c++ - 当 ptr_vector 迭代器失效时

转载 作者:行者123 更新时间:2023-11-30 02:00:32 25 4
gpt4 key购买 nike

是否有可能插入和/或删除元素会使现有元素的迭代器无效。

谢谢。

最佳答案

是的。 documentation对于 boost::ptr_vector<T>状态:

A ptr_vector<T> is a pointer container that uses an underlying std::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/

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