Last active
November 16, 2015 16:00
-
-
Save STrix8/b2d7178ccd432d0bf17b to your computer and use it in GitHub Desktop.
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
#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; | |
} |
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
#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; | |
}; |
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
#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