Re: STL vector and push_back
- From: Martin Eisenberg <martin.eisenberg@xxxxxxx>
- Date: Fri, 30 Jun 2006 12:08:03 +0000 (UTC)
Abstract Dissonance wrote:
I'm working with STL vector and trying to get in the habit of
using iterators to work through the vector instead of "direct
indexing". It doesn't seem all that difficult as they seem to
work like pointers but I'm having a problem when I create an
iterator for a vector then push something onto the end of vector
with push_back it will "destory" my iterator(I'm not sure
exactly what happens but the iterator becomes useless... not
sure if it gets set to s.end() or what).
For all you, the user, know, nothing happens to the iterator as
stored in memory. Invalidation is a logical notion that may not be
reflected by any bits changing. Nevertheless the only defined
operation on an invalidated iterator is reassignment.
If you know in advance how many items you will at most insert, call
reserve() on the vector before populating it. This will both give you
speed by avoiding repeated allocations and copies, and keep
iterators, references, and pointers into the vector valid -- though
obviously, if you assume so then better be sure that the supposed
upper size bound is right.
Now I might see why this would happen because you are changing
the vector and it could cause problems in certain situations but
I need to keep the current position of the iterator. This could
easily be done using indexing but I'm trying to get away from
that.
Whether that makes sense depends on the situation -- indices are no
less valid a tool than iterators. The main value of iterators is that
they decouple working on a sequence of values from the exact way
those values are held; i.e., they let you reason about code on a
higher level. They let you focus on the access characteristics an
algorithm requires (sequential vs. random access, say) instead of
container class minutiae. This does not apply to your example code
which needs the container itself anyway.
That said, if you have the time you might understand it best if you
stay away from indices until you're reasonably fluent with iterators
and they start to really annoy you in certain situations, then switch
back to pure indexing for a while and see what you miss from the
iterator approach ;)
Martin
--
Quidquid latine scriptum sit, altum viditur.
.
- References:
- STL vector and push_back
- From: Abstract Dissonance
- STL vector and push_back
- Prev by Date: Re: ls lacking a feature?
- Next by Date: Re: ls lacking a feature?
- Previous by thread: Re: STL vector and push_back
- Index(es):
Relevant Pages
|