如何制作循环缓冲区? [英] How to make a circular buffer?

查看:82
本文介绍了如何制作循环缓冲区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为类创建数组中的循环缓冲区,但我不太了解如何实现该概念.我知道有些索引可以来回移动,但是我并不真正了解它是如何实现的.您甚至如何为数组的元素分配尾部或头部,或者如何对它们进行索引?任何建议,代码或解释都将非常有帮助.

解决方案

循环缓冲区基本上只是一个数组和两个整数,用于跟踪您认为是尾巴"和头"的位置./p>

空缓冲区以相同的索引处的"tail"和"head"开头( 0 是任何一个都不错的选择).

当添加到缓冲区时,将在尾"点添加的位置插入,然后将尾巴移至下一个位置.之所以成为圆形",是因为当尾巴"从数组的末端掉落时,它会跳回其开头(索引为0).

类似地,您可以通过查看并调整各自的位置从头端或尾端将其从缓冲区中移出.

I have to make a circular buffer out of an array for class and I can't quite grasp how the concept is implemented. I get that there are are indexes that go back and forth but I don't really understand how this is actually implemented. How do you even assign a tail or head to elements of an array, or index them both ways? Any advice, code or explanation would be extremely helpful.

解决方案

A circular buffer is basically just an array and two integers that keep track of the positions that you consider to be the "tail" and the "head".

The empty buffer starts out with both "tail" and "head" at the same index (0 is as good a choice as any).

When you add to the buffer, you insert at where the "tail" points add, and then move the tail to next position. It gets "circular" because when the "tail" falls off the end of the array, it jumps back to its beginning (index 0).

Similarly, you remove from the buffer from either head or tail end by looking at and adjusting the respective positions.

这篇关于如何制作循环缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆