TL;DR:
- The "shift" is done when the buffer has been filled and if the head is not at the end of it. If you pop each time that you push, there is no need to move the data.
- Values are not contiguous because they wrap around the buffer.
The VecDeque
has 2 internal indices: one for the head and one for the tail. When you push or pop things into/from the VecDeque
, either the head or tail is incremented/decremented accordingly.
First case: the buffer is not full
Let's see what happen where there is one call to push_back
and pop_front
.
The head is not at the last index in the buffer
T H
Before [o o o o . . . . ]
T H
After [. o o o o . . . ]
The head arrives at the last index in the buffer
You just wrap the buffer around. The buffer is now split in two parts.
H T
Before [. . . . o o o o ]
H T
After [o . . . . o o o ]
Second case: the buffer is full
When the internal buffer is filled and you push another thing, you have three scenarios described in the code:
The head is at the end of the buffer
The buffer only grows.
T H
Before [o o o o o o o . ]
T H
After [o o o o o o o . . . . . . . . . ]
The head is shorter than the tail
After the buffer grows, the head is moved after the tail.
H T
Before [o o . o o o o o ]
T H
After [. . . o o o o o o o . . . . . . ]
The tail is shorter than the head
After the buffer grows, the tail is moved to the end of the buffer.
H T
Before [o o o o o . o o ]
H T
After [o o o o o . . . . . . . . . o o ]