Suppose I have a vector of ints,
std::vector numbers;
that is populated with a bunch of values, then I say do this (where an ent
Pointers, references, and iterators to std::vector
elements are guaranteed to stay put as long as you only append to the std::vector
and the size of the std::vector
doesn't grow beyond its capacity()
at the time the pointer, reference, or iterator was obtained. Once it gets resized beyond the capacity()
all pointers, references, and iterators to this std::vector
become invalidated. Note that things are invalidated as well when inserting somewhere else than the end of the std::vector
.
If you want to have your objects stay put and you only insert new elements at the end or the beginning, you can use std::deque
. Pointers and references to elements in the std::deque
get only invalidated when you insert into the middle of the std::deque
or when removing from the middle or when removing the referenced object. Note that iterators to elements in the std::deque
get invalidated every time you insert an element into the std::deque
or remove any element from it.