Skip to content

Instantly share code, notes, and snippets.

@dpkoch
Created April 24, 2016 17:56
Show Gist options
  • Save dpkoch/28582ffb8dec46d4e72085c683d4fa83 to your computer and use it in GitHub Desktop.
Save dpkoch/28582ffb8dec46d4e72085c683d4fa83 to your computer and use it in GitHub Desktop.
#ifndef CIRCULAR_BUFFER_H
#define CIRCULAR_BUFFER_H
#include <stdlib.h>
template <class T>
class CircularBuffer
{
private:
T* data;
size_t cp;
size_t sz;
size_t idx;
public:
CircularBuffer(size_t capacity)
{
cp = capacity;
data = new T[cp];
sz = 0;
idx = 0;
}
~CircularBuffer()
{
delete[] data;
}
void add(T element)
{
data[idx] = element;
idx++;
idx %= cp;
if (sz < cp)
sz++;
}
size_t capacity()
{
return cp;
}
size_t size()
{
return sz;
}
T sum()
{
T sum = static_cast<T>(0);
for (size_t i = 0; i < sz; i++)
{
sum += data[i];
}
return sum;
}
};
#endif // CIRCULAR_BUFFER_H
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment