Last active
February 4, 2020 21:19
-
-
Save jvanwinden/93a9b4b4433e1f20de97 to your computer and use it in GitHub Desktop.
C++ Ringbuffer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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