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

标签 c++ boost boost-ptr-container

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

谢谢。

最佳答案

是的。 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/

相关文章:

C++ 帮助 boost::ptr_map/boost::checked_delete 失败

c++ - 每帧调用 glGetUniformLocation()

C++ 使用暂停/恢复控件下载文件

c++ - 如何从其他文件访问 GTKMM 小部件?

c++ - 将 Boost 与 getter 和 setter 结合使用?

c++ - Boost Pointer Container - 不能将类存储为 ptr_map 的键

c++ - 如何以 36 进制输入数字?

c++ - 使用 boost 正则表达式时出现 shared_ptr 错误

c++ - 将 std::string 转换为 boost::posix_time::ptime