21 explicit RingBuffer(
size_t capacity = 0) : _capacity(capacity), _head(0), _count(0) {
23 _data.resize(_capacity);
33 _data.resize(capacity);
44 if (_capacity == 0)
return;
46 if (_count < _capacity) {
51 size_t insert_idx = (_head + _count) % _capacity;
52 _data[insert_idx] = val;
57 _head = (_head + 1) % _capacity;
69 return _data[(_head + i) % _capacity];
79 return _data[(_head + i) % _capacity];
88 return (*
this)[_count - 1];
97 return (*
this)[_count - 1];
101 size_t size()
const {
return _count; }
104 bool empty()
const {
return _count == 0; }
107 bool full()
const {
return _count == _capacity; }
130 std::vector<T> _data;
A fixed-capacity ring buffer (circular buffer).
Definition: ring_buffer.hpp:15
void set_capacity(size_t capacity)
Resizes and resets the buffer.
Definition: ring_buffer.hpp:31
bool empty() const
Checks if the buffer is empty.
Definition: ring_buffer.hpp:104
void clear()
Clears the buffer content.
Definition: ring_buffer.hpp:112
void push_back(const T &val)
Pushes a new element into the buffer.
Definition: ring_buffer.hpp:43
size_t size() const
Returns the number of elements currently stored.
Definition: ring_buffer.hpp:101
const T & operator[](size_t i) const
Construct element by logical index (0 is oldest).
Definition: ring_buffer.hpp:77
T & operator[](size_t i)
Access element by logical index (0 is oldest).
Definition: ring_buffer.hpp:67
const T & back() const
Access the newest element (const).
Definition: ring_buffer.hpp:95
bool full() const
Checks if the buffer is full.
Definition: ring_buffer.hpp:107
RingBuffer(size_t capacity=0)
Constructs a RingBuffer with a given capacity.
Definition: ring_buffer.hpp:21
void reserve(size_t n)
Reserve capacity (resets buffer if new capacity > old capacity).
Definition: ring_buffer.hpp:122
T & back()
Access the newest element.
Definition: ring_buffer.hpp:86