Created
August 9, 2016 16:41
-
-
Save simogasp/09807f55e2ad1360c456972b3551bff9 to your computer and use it in GitHub Desktop.
LimitedBuffer that pops element from front when inserting if maxSize is reached
This file contains hidden or 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
// 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