14

The VecDeque documentation says that it uses a growable ring buffer as implementation.

How does it work internally?

  • In the case when I only use it as a queue (only push_back and pop_front), when is the shifting done? Each time I call pop_front? When the internal buffer reaches a critical size?
  • Why are there two slices (one for the back, one for the front)? Are they not contiguous?
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Boiethios
  • 38,438
  • 19
  • 134
  • 183

1 Answers1

15

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 ]
Boiethios
  • 38,438
  • 19
  • 134
  • 183