"JackC" <je******@gmail.comwrote in message
news:11**********************@o38g2000hse.googlegr oups.com...
Hi,
I am trying to find if its at all possible to create a pointer to an
object inside a vector, based upon a vector iterator that will remain
a valid pointer once the iterator is invalid.
For example I just tried:
for(vector<ship>::iterator invader = shooters.begin(); invader !=
shooters.end(); )
{
...
Ship.parent = &(*invader);
...
}
With the aim being that parent points to the item inside the invader
vector throughout the life of the vector, but instead the pointer
becomes invalid when the iterator is invalidated.
Any solutions to this problem?
Not really. When the vector invalidates an iterator, that generally means
that the object itself has moved in memory. If it has moved in memory, then
your pointer is going to become invalid. Now, you can save the index of it,
but that index can also change (something was deleted in front of this one,
shifting it's index down one).
The only real way to fix this if you have to do it is to either store
pointers in the first place (using new, delete and pushing the pointer) or
use some other type of container where the index won't be invalidated, or
that uses a key you can store.
It all depends on how important it is to you to have a pointer to the
instance that doesn't become invalidated.