CircularBuffer<type> class overview
The CircularBuffer<type> class stores elements in an array and
keeps track of the most recent element and also keeps track of
one reading index. Also elements can be accessed as an index
relative to the last written element.
CircularBuffer Figure 1
|
|
|
To add an element to a CircularBuffer object, use the insert
function as shown in Example 1. There are two methods of geting values
from the circular buffer which are also demonstrated in Example 1:
- by array index -- The buffer can be treated like a regular array
where the 0-index value was the last one written to the buffer.
The previously written element is found at the -1 index
location. To prevent confusion about the negative indices, the
positive indices are translated into negative values before they
are used.
- by extraction -- There is a end-of-buffer reading pointer
which can be updated by calling the extract function.
When the extract function is called, then the read pointer
will be updated and an element storage space is freed up for writing
later on. If the writing pointer runs into the reading pointer, then
the writing pointer will push the reading pointer forward one element
and erase the old read storage location for its own use.
CircularBuffer Example 1: writing elements to the buffer |
|
|
CircularBuffer<int> buffer(10); // buffer with 10 elements
buffer.insert(67);
buffer.insert(43);
buffer.insert(59);
// two ways to read a CircularBuffer:
// method 1: by array index
buffer[0]; // return value: 59
buffer[-1]; // return value: 43
buffer[-2]; // return value: 67
buffer[1]; // return value: 43 (positive indices map to negative)
// method 2: by extraction
buffer.extract(); // return value: 67
buffer.extract(); // return value: 43
buffer.extract(); // return value: 59
|
|
The CircularBuffer class is a template class, so it
can hold any type of data. In Example 1 above, the storage type
was int as specified in the first line of the example.
Useful maintenance functions include:
capacity |
returns how many free spaces are left in the circular buffer.
|
getCount |
returns the number of elements currently in the buffer.
|
getSize |
returns the maximum number of elements which can be stored
in the buffer.
|
CircularBuffer Example 2 |
|
|
CircularBuffer<int> buffer(10); // buffer with 10 elements
buffer.insert(67);
buffer.insert(43);
buffer.insert(59);
buffer.capacity(); // should return value: 7
buffer.getCount(); // should return value: 3
buffer.getSize(); // should return value: 10
|
|