I have been using std::vector
a lot, and recently I asked myself this question: \"How is std::vector
implemented?\"
I had two alternatives:
Section 23.2.4, ¶1 of the standard requires that arithmetic on pointers into a vector work the same as with pointers into an array.
The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().
This guarantees that the storage is in an array. Of course, if you resize the array to be bigger, it might get moved in memory.
They use a dynamically allocated array that is regrown as needed. It is necessary to use something like an array so that the elements are contiguous in memory which is guaranteed by the standard.
Incidentally, one common way of regrowing an array is to double the size as needed. This is so that if you are inserting n
items at most only O(log n)
regrowths are performed and at most O(n)
space is wasted.
You can read one implementation for yourself at SGI (where STL was originally conceived).
I believe the STL uses option #2 (or something similar) because a std::vector<> is guaranteed to store the elements in contiguous memory.
If you're looking for a memory structure that doesn't need to use contiguous memory, look at std::deque.