We want to implement a templated circular buffer class, circular_buffer<T>, that supports push_back(), pop_front(), size(), and the [] operator.
A circular buffer behaves similar to a circular queue introducted in the Data Struecutre textbook except that a newly inserted element may replace an old element if the buffer is full. Specifically, if a circular buffer is full, the front element of the buffer is popped before a new element is inserted.
Please use the following partial code to complete this homework.
#include <iostream>
using namespace std;
/* Code for our templated circular buffer class goes here */
int main()
{
int capacity;
cin >> capacity;
circular_buffer<int> cbi(capacity);
int N;
cin >> N;
for(int i=0; i<N; i++){
string cmd;
cin >> cmd;
if(cmd=="push_back"){
int data;
cin >> data;
cbi.push_back(data);
}else if(cmd=="pop_front"){
cbi.pop_front();
}else if(cmd=="print"){
for(int j=0; j<cbi.size(); j++){
cout << cbi[j] << endl;
}
cout << "----" << endl;
}
}
return 0;
}
Please note that the partial code can handle input and output already. We do not need to rewrite this part of input/output handling code. We only need to focus on the circular buffer class. Input and output format are listed for reference only.
The first input integer indicates the capacity of the capacity of the instantiated circular buffer.
The second input integer indicates the number of commands used to test the buffer.
Commands include
push_back k : insert an interger, k, using the push_back() operator
pop_pront : remove an element, using the pop_front() operator
print : print out all elements in the buffer using the [] operator and a loop.
Please note that the partial code can handle input and output already. We do not need to rewrite this part of input/output handling code. We only need to focus on the circular buffer class. Input and output format are listed for reference only.
Upon a print command all elements in the buffer are printed out, starting at the front and working toward the back.