Reply To: C++ Programming
My new book has been telling me more about Vectors and C++ style strings.
The elements in a Vector must be stored continuosly in memory so that they can be accessed by an index number. If you initialize a vector with an initial number of elements using square brackets, “” say, or a list of initial elements then the vector will be allocated enough memory for them ONLY to start with.
If you use the push_back function to add another element to the end of the list then more memory will need to be allocated. To make sure that the memory remains contiguous the Vector function needs to assign a new bigger block and then copy the existing elements into that before deleting the originals. The Vector function ensures that the Vector name now points to the new block. This time round the Vector function assigns more memory than the new Vector will need and the amount is implementation specific. You can use the Capacity function in Vector to find out how much extra you have.
The other point to note is that the elements in a Vector are only pointers or “vectors” to the actual data the Vector holds so that data does not move when a Vector is expanded, that and the extra capacity makes expanding Vectors quick.
C++ std library strings work in a similar way but their elements actually do hold the charachte data.