OK, I’d like to clear something once and for all. If I have a normal vector, like:
std::vector<Object*> coll;
and I want to go through its elements, I know three ways to go about it:
1. Using int index, such as: for(int i = 0; i < coll.size(); ++i)
2. Using type_t index, same as 1.: for(size_t i = 0; i < coll.size(); ++i)
and access elements in both 1 and 2 by: coll[i]
or
3. Using const_iterator, as in:
std::vector<Object*>::const_iterator i;
for(i = coll.begin(); i != coll.end(); ++i)
// stuff
and access elements with *it.
I’ve noticed (and heard) that the third way is the most fail-proof one, but it’s quite unpleasant when it comes to deallocating the vector, because when I use const_iterator, if I do something like delete (*it), or even coll.erase(it) before deallocating, my iterator loses its value, and then I can’t continue with the for loop.
What’s the suggested/good way to do this?
Your first two approaches are both not entirely correct. The correct index type is
This is what size() returns, and it is what operator[] takes.
The approach using iterators is the idiomatic one. You wrote
This is not correct. In something like
You don’t invalidate the iterator
it. You merely calldeleteon what the iterator points to. So you can safely advance the iterator after thedelete.