jl*****@earthli nk.net (Jessica) wrote in
news:d1******** *************** ***@posting.goo gle.com:
Ah. Thanks guys. That explains the strange exceptions that I've been
getting. So when should reserve() be used? I guess what confused me
is this paragraph that I read from SGI:
"Reserve() causes a reallocation manually. The main reason for using
reserve() is efficiency: if you know the capacity to which your vector
must eventually grow, then it is usually more efficient to allocate
that memory all at once rather than relying on the automatic
reallocation scheme. The other reason for using reserve() is so that
you can control the invalidation of iterators."
Thank you again!
No problem :)
Reserve is good if you know ahead of time that you are going to be doing
a bunch of push_back() (or using back_inserter) on your vector. Recall
that vector will automatically resize to fit the number of objects.
Let's assume that you start with an empty vector, and you start pushing
on 10000 objects. (Note that the reallocation scheme I'm going to use
isn't necessarily the one your vector uses, but it uses something along
the same idea).
The vector assumes that you are going to push some items on it, so it
preallocated space for 16 items.
Your first 16 push_backs simply copy your items into those 16 spaces.
The 17th push_back causes a reallocation. Space for 32 objects is
created, and the first 16 objects are copied into this new space. The
old space is deallocated, and then the new object is copied into the 17th
space.
The next 15 push_backs simply copy the items into the 18th through 32nd
space.
The 33rd push_back causes a reallocation. Space for 64 objects is
created, the first 32 objects are copied, etc....
At the 65th push_back this happens again (space for 128)
Again at 129, 257, 513, 1025, 2049, 4097, and 8193. Finally you have a
vector containing 10000 objects, and has space for 16k objects.
Constrast this with calling reserve first.
You start by doing a .reserve(10000) on the vector. You then start doing
your push_backs. All 10000 will be copied into the vector. No more
reallocations, and no "extra" copies of objects being made. (Recall that
in the first scenario, the first object that you push_back()ed into the
vector is copied an extra 10 times as it's moved from each allocation to
the next new allocation).
So by calling reserve first, you save 10 extra dynamic memory
allocations, and thousands of extra copies of objects.