Re: pointer iterator interaction
Robbie Hatley wrote:
"silversurfer" <kietzi@web.de> wrote:
Ok, this should be fairly easy for most of you (at least I hope so),
but not for me:
Let us say we have got the following elements:
std::vector<Entry> models; //Entry is a struct
std::vector<Entry>::iterator modelIterator;
In a method, I am currently writing, I need to get a pointer to an
entry in the vector.
No you don't. Don't use pointers to elements in Vectors.
Pointers to elements in vectors tend to get "stale", because
vectors reallocate themselves if they grow, so you'd eventually
end up dereferencing wild pointers and crashing your program.
The exact same is true for iterators into vectors.
I thought of the following:
Entry* MyObject::getNextEntry() {
Entry* tmpEntry;
if (modelIterator == models.end()) {
return NULL;
} else {
tmpEntry = modelIterator;
modelIterator++;
return tmpEntry;
}
}
Unfortunately, this does not work
Of course it doesn't work. The return type of your function is:
Entry*
but the type of tmpEntry is:
std::vector<Entry>::iterator
The two types are not even remotely similar.
They might actually be the same type, but it's implementation defined.
How can I get a pointer to the element to which the iterator
is currently pointing?
If you absolutely MUST do that, then you can, easily, like so:
Entry* DangerousPointer = &(*modelIterator);
But that is very dangerous. For iterating through the elements
of a Vector, use real iterators. You can use iterators for (almost)
anything you could use pointers for.
In which way would an iterator be safer here?
Or use integer subscripting. With vectors, that's often easier than
using iterators, and you don't need to worry about whether an old
iterator still points to something valid.
Might be a bit slower though, but usually that can be ignored.