I think the diagram will be better for you ... let him play with ASCII art!
Deque is usually an array of chunks of memory, but everything about the front and rear memory blocks is full. This is necessary because deque is a RandomAccessContainer, and in order to access O (1) to any container, you cannot have an unlimited number of containers from which you can read the size:
bool size() const { return first.size + (buckets.size()- 2) * SIZE + last.size; } T& operator[](size_t i) { if (i < first.size) { return first[SIZE - i]; } size_t const correctedIndex = i - first.size; return buckets[correctedIndex / SIZE][correctedIndex % SIZE]; }
These operations are O (1) due to multiplication / division!
In my example, I assume that the memory block is full when it contains 8 elements. In practice, no one said that the size should be fixed, just so that all the inner buckets are the same size.
Now tell us what we want to insert in index 13. It falls somewhere in a bucket with the inscription 2. There are several strategies that we can think of:
- expand bucket 2 (only)
- insert a new bucket before or after 2 and shuffle only a few items
But these two strategies would violate the invariant that all "inner" buckets have the same number of elements.
Therefore, it remains for us to mix the elements around, either to the beginning or to the end (depending on which is cheaper), in our case:
Notice how bucket 0 increased.
This random move means that in the worst case you will move half of the elements: O (N / 2).
deque
has O (1) inserted either at the beginning or at the end, because there it is simply a matter of adding an element to the right place or (if the bucket is full), creating a new bucket.
There are other containers that have better insert / delete behavior for random indexes based on B + Trees . In an indexed B + Tree, you can instead of holding a "key" (or in parallel) maintain the number of elements inside you to a certain position. For effective work, there are various techniques. At the end, you get a container with:
- O (1): empty, size
- O (log N): at, insert, erase
You can check the blist
module in Python, which implements a list item like Python, supported by such a structure.