Skip to content

Instantly share code, notes, and snippets.

@jvanwinden
Last active February 4, 2020 21:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jvanwinden/93a9b4b4433e1f20de97 to your computer and use it in GitHub Desktop.
Save jvanwinden/93a9b4b4433e1f20de97 to your computer and use it in GitHub Desktop.
C++ Ringbuffer
#ifndef RINGBUFFER_H
#define RINGBUFFER_H
#include <stdexcept>
template <class T>
class Ringbuffer {
public:
explicit Ringbuffer(const int size);
~Ringbuffer();
T & get();
void add(const T & val);
int size();
bool full();
bool empty();
private:
int n_elements;
T * arr;
const int arr_size;
int start;
int end;
};
template <class T>
Ringbuffer<T>::Ringbuffer(const int size) :
arr_size(size),
arr(new T[size]),
start(0),
end(-1),
n_elements(0) {}
template <class T>
Ringbuffer<T>::~Ringbuffer() {
delete[] arr;
}
template <class T>
T & Ringbuffer<T>::get() {
if (empty()) {
throw std::out_of_range("Ringbuffer<>::get(): buffer is empty");
}
n_elements--;
return arr[start++ % arr_size];
}
template <class T>
void Ringbuffer<T>::add(const T & value) {
if(full()) {
throw std::out_of_range("Ringbuffer<>::add(): buffer is full");
}
n_elements++;
arr[++end % arr_size] = value;
}
template <class T>
int Ringbuffer<T>::size() {
return n_elements;
}
template <class T>
bool Ringbuffer<T>::full() {
return size() == arr_size;
}
template <class T>
bool Ringbuffer<T>::empty() {
return size() == 0;
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment