Now we can create a new CircularBuffer with a set size and get its string representation so we can print it to the screen.
Note that we are making a list of a fixed size and that we have a head, tail, and max_size property.
Next, let’s create some helper methods to give us the size of our buffer and check if it’s empty or full:You might be wondering why are we using self.
tail == (self.
head-1) % self.
max_size to determine if the buffer is full.
Well we want to say the buffer is full one before the head to make sure we don’t overwrite the head and that is why we do (self.
We modulus (self.
head-1) by self.
max_size since our head is moving along with the tail, we want to get a number back that represents where the position would be in relation to the size.
For example, if the max_size is 10, our head is at index 0 and the tail is at index 9, the method should return True as 9 == (0-1) % 10.
Now that we have our helper methods, let’s implement the actual methods we need to work with our circular buffer: enqueue, dequeue, and front.
Here’s the code:To enqueue or add an item to the buffer, we first have to check that the buffer is not full.
Then we set the data at the tail index equal to the item and update the tail.
Similar to the is_full method we have to use modulus to update our tail since the head and tail indexes are moving “around the circle”.
Dequeue is similar except we are clearing the data at the head index, updating the head index to be the next item, and returning the head data before the update.
Finding the item at the front of the buffer is as easy as returning the data at the head index.
That’s all the code we need for a working circular buffer implementation in Python!.Here is the full code as a reference:As promised, below is an implementation in C++.
Note that I will be using smart pointers to make things easier and a template class so we can create circular buffers that hold different types of data such as a circular buffer of unsigned integers or a circular buffer of strings.
Here’s the code:Thank you for reading!.Please leave comments below if you have any suggestions or questions.
.. More details