I was asked this question in an interview, and didn't go through. I know, it needs some improvements, but probably I am missing something big? I would highly appreciate if someone can review it for me, so that I can get to know what I need to work on.
The problem is to complete this skeleton class to implement a circular buffer. I could have done the C++ and header in a different source, but they insisted on doing it all here, assuming it is not part of a big project.
class CircularBuffer {
public:
CircularBuffer(int size)
: data_(size, 0)
, next_(0)
, head_(-1)
{
}
~CircularBuffer()
{
}
bool empty()
{
return size() == 0;
}
int size()
{
// TODO: check if head is valid.
// TODO: check emptiness properly.
int sz = 0;
if (head_ >= 0)
{
if (next_ > head_)
sz = next_ - head_;
else
sz = next_ + (data_.size() - head_);
}
return sz;
}
void push(char val)
{
// TODO: check if circularbuffer is full.
if( size() == data_.size())
{
std::cout<<"Buffer is full, can't push anything"<< std::endl;
return;
}
data_[next_++] = val;
if(head_ < 0)
head_ = 0;
if (next_ == data_.size())
next_ = 0;
displayBuffer();
}
char pop()
{
// TODO: check if head_ is valid.
if (head_ < 0)
{
std::cout<<"Empty Buffer, nothing to pop" << std::endl;
return -1;
}
// TODO: adjust head_ after pop.
char popVal = data_[head_];
data_[head_++] = 0; // Clean the popped memory- display purpose
//Wrap around head_ move
if (head_ == data_.size())
head_ = 0;
// Check if the buffer is empty now?
if (head_ == next_)
{
head_ = -1; //Buffer is empty now
next_ = 0;
}
return popVal;
}
void displayBuffer()
{
std::cout << std::endl;
for (auto c: data_)
{
std::cout << c << ' ';
}
std::cout << " | HEAD = " << head_ << " NEXT = " << next_ << std::endl;
}
private:
std::vector<char> data_;
int next_;
int head_;
};