Skip to content

Instantly share code, notes, and snippets.

@simogasp
Created August 9, 2016 16:41
Show Gist options
  • Save simogasp/09807f55e2ad1360c456972b3551bff9 to your computer and use it in GitHub Desktop.
Save simogasp/09807f55e2ad1360c456972b3551bff9 to your computer and use it in GitHub Desktop.
LimitedBuffer that pops element from front when inserting if maxSize is reached
// queue::push/pop
#include <iostream> // std::cin, std::cout
#include <deque> // std::queue
#include <assert.h>
template<class T>
class LimitedBuffer
{
private:
typedef std::deque<T> Buffer;
Buffer _buffer;
std::size_t _maxSize;
public:
LimitedBuffer(std::size_t maxSize) : _maxSize(maxSize) { }
typedef typename Buffer::iterator iterator;
typedef typename Buffer::const_iterator const_iterator;
iterator begin() { return _buffer.begin(); }
iterator end() { return _buffer.end(); }
const_iterator begin() const { return _buffer.begin(); }
const_iterator end() const { return _buffer.end(); }
void push_back(T &fm)
{
assert(_buffer.size() <= _maxSize);
if(_buffer.size() == _maxSize)
{
_buffer.pop_front();
}
_buffer.push_back(fm);
}
};
template<class T>
void printLimitedBuffer(const LimitedBuffer<T>& lb)
{
for(const T& elem : lb)
std::cout << elem << "\t";
std::cout << std::endl;
}
int main ()
{
LimitedBuffer<int> myqueue(4);
int myint;
std::cout << "Please enter some integers (enter 0 to end):\n";
do {
std::cin >> myint;
myqueue.push_back(myint);
std::cout << "Contains: " ;
printLimitedBuffer(myqueue);
} while (myint);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment