How is std::vector
implemented, using what data structure? When I write
void f(int n) {
std::vector v(n);
...
}
Is
The vector
object will be allocated on the stack and will internally contain a pointer to beginning of the elements on the heap.
Elements on the heap give the vector
class an ability to grow and shrink on demand.
While having the vector
on the stack gives the object the benefit of being destructed when going out of scope.
In regards to your []
question, the vector
class overloads the []
operator. I would say internally it's basically doing something like this when you do array[1]
:
return *(_Myfirst+ (n * elementSize))
Where the vector
keeps track of the start of it's internal heap with _Myfirst
.
When your vector
starts to fill up, it will allocate more memory for you. A common practice is to double the amount of memory needed each time.
Note that vector
inherits from _Vector_val
, which contains the following members:
pointer _Myfirst; // pointer to beginning of array
pointer _Mylast; // pointer to current end of sequence
pointer _Myend; // pointer to end of array
_Alty _Alval; // allocator object for values