C++ 'growing' arrays

Started by
9 comments, last by iMalc 12 years, 9 months ago

Hello,

@Wooh: That is not true in all cases. If you have a pointer (for example) pointing to the last element of the list, adding past it is a trivial matter because you don't need to go through all the elements to get there. And std::list does have an iterator to the end of the list. In case of vector, if the number of allocated elements is not enough anymore (the capacity of the vector), when you try to add to it, it may need to allocate a new memory space, move all existing elements in that memory space, and free the old one.
So what?! In the long run each item still only needs to be copied for resizing purposes about once on average.
Count the number of copies that would occur with a vector initially containing one item and having say 255 more items added:
1 + 2 + 4 + 8 + 16 + 32 + 64 + 128 = total 255 copies for 256 items. It's always roughly constant due to the way a vector grows.
"In order to understand recursion, you must first understand recursion."
My website dedicated to sorting algorithms

This topic is closed to new replies.

Advertisement