Skip to content

Instantly share code, notes, and snippets.

@STrix8
Last active November 16, 2015 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save STrix8/b2d7178ccd432d0bf17b to your computer and use it in GitHub Desktop.
Save STrix8/b2d7178ccd432d0bf17b to your computer and use it in GitHub Desktop.
RingBuffer
#include "ringbuffer.hpp"
#include <vector>
using namespace std;
template <typename T>
RingBuffer<T>::RingBuffer(int size) {
array= new vector<T*>(size);
top = 0;
tail = 0;
indexNum = size;
}
template <typename T>
void RingBuffer<T>::push(T data) {
*(array[tail++]) = data;
tail %= indexNum;
if (tail == top) {
++top;
}
}
template <typename T>
T RingBuffer<T>::pop(void) {
T ret = *(array[top++]);
if (top > tail) {
++tail;
}
return ret;
}
template <typename T>
T RingBuffer<T>::get(int index) {
return *(array[(top + index) % indexNum]);
}
template <typename T>
T RingBuffer<T>::operator [](int index) const {
return *(array[index]);
}
template <typename T>
RingBuffer<T>::~RingBuffer() {
delete array;
}
#pragma once
#include <vector>
template <typename T>
class RingBuffer {
public:
RingBuffer(int size);
void push(T data);
T pop(void);
T get(int index);
T operator [](int index) const;
~RingBuffer();
private:
std::vector<T*>* array;
int top;
int tail;
int indexNum;
};
#include <iostream>
#include "ringbuffer.hpp"
using namespace std;
int main(void) {
RingBuffer<int> rg(5);
for (int i = 0; i < 5; ++i) {
cout << "rg[" << i << "]: " << rg.get(i) << endl;
}
for (int i = 1; i <= 5; ++i) {
cout << "push: " << i << endl;
rg.push(i);
for (int j = 0; j < 5; ++j) {
cout << "rg[" << j << "]: " << rg[j] << " ";
}
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment