VecDeque环缓冲区如何在内部工作?

问题描述 投票:4回答:1

VecDeque documentation说它使用可增长的环形缓冲区作为实现。

它在内部如何运作?

  • 在我只将它用作队列(仅push_backpop_front)的情况下,何时进行转换?每次我打电话给pop_front?当内部缓冲区达到临界尺寸?
  • 为什么有两个切片(一个用于背面,一个用于正面)?他们不是连续的吗?
collections rust queue
1个回答
7
投票

TL; DR:

  • 当填充缓冲区并且头部不在其末尾时,完成“移位”。如果每次推送都弹出,则无需移动数据。
  • 值不是连续的,因为它们环绕缓冲区。

VecDeque有2个内部指数:一个用于头部,一个用于尾部。当你向/从VecDeque推送或弹出东西时,头部或尾部相应地递增/递减。

First case: the buffer is not full

让我们看看在有一次调用push_backpop_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

你只需将缓冲区包裹起来。缓冲区现在分为两部分。

        H       T
Before [. . . . o o o o ]
          H       T
After  [o . . . . o o o ]

Second case: the buffer is full

当内部缓冲区被填满并且你推送另一个东西时,你有三个场景描述in the code

The head is at the end of the buffer

缓冲区只会增长。

        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

缓冲区增长后,头部在尾部后移动。

            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

缓冲区增长后,尾部移动到缓冲区的末尾。

                  H T
Before [o o o o o . o o ]
                  H                 T
After  [o o o o o . . . . . . . . . o o ]
© www.soinside.com 2019 - 2024. All rights reserved.