Dynamic Memory Assignment in Vector

advertisements

I have a doubt regarding memory allocation in vector(STL - C++). As far as I know, its capacity gets doubled dynamically every time the size of vector gets equal to its capacity. If this is the case, how come the allocation be continuous? How does it still allow to use the [] access operator for O(1) access just like arrays? Can anyone explain this behavior? (List also has dynamic memory allocation but we cannot access its elements using [] access operator, how is it still possible with vector? )

#include<iostream>
#include<vector>
using namespace std;

int main() {
    // your code goes here
    vector<int> v;

    for(int i=0;i<10;i++){
        v.push_back(i);
        cout<<v.size()<<" "<<v.capacity()<<" "<<"\n";
    }

    return 0;
}

Output:

1 1
2 2
3 4
4 4
5 8
6 8
7 8
8 8
9 16
10 16


As far as I know, its capacity gets doubled dynamically every time the size of vector gets equal to its capacity.

It does not need to double like in your case, it's implementation defined. So it may differ if you use another compiler.

If this is the case, how come the allocation be continuous?

If there is no more continuous memory which the vector could allocate, the vector has to move it's data to a new continuous memory block which meets it's size requirements. The old block will be marked as free, so that other can use it.

How does it still allow to use the [] access operator for O(1) access just like arrays?

Because of the facts said before the access will be possible with the [] operator or a pointer + offset. The access to the data will be O(1).

List also has dynamic memory allocation but we cannot access its elements using [] access operator, how is it still possible with vector?

A list (std::list for example) is totally different from a std::vector. In the case of a C++ std::list it saves nodes with data, a pointer to the next node and a pointer the previous node (double-linked list). So you have to walk through the list to get one specific node you want. Vectors work like said above.