The ring queue of boost library is flexible. It supports forward or backward insertion, deletion of the first or last element of the queue.
Paste code only:
#include
#include
#include
#include
using namespace std;
class C_usrdata{
public:
int x;
int y;
};
void DispCirBuff(boost::circular_buffer &oCircularBuffer){
for(boost::circular_buffer::iterator it=oCircularBuffer.begin(); it!=oCircularBuffer.end(); it++){
cout << (*it).x << " " << (*it).y << endl;
}
cout << endl;
}
int main(int argc, char*argv[])
{
//Create a circular buffer with a capacity of 3
boost::circular_buffer cb(3);
//Insert some elements into the circular buffer
C_usrdata data1 = {1, 1.34};
C_usrdata data2 = {2, 2.34};
cb.push_back(data1);
cb.push_back(data2);
//Assertion
cout << cb[0].y << endl;
assert(!cb.full());
assert(cb.size() == 2);
assert(cb.capacity() == 3);
cout << " running ok" << endl;
//Insert other elements
C_usrdata data3 = {3, 3.34};
cb.push_back(data3);
Cout < "when the queue is full, continue to insert elements -- Experiment" < endl;
C_usrdata data4 = {4, 4.34};
cb.push_back(data4);
//When the queue is full, continue to insert the element, the first element will be squeezed out.
//Prediction: at this time, the data in the queue should be: data2 data3 Data4
DispCirBuff(cb);
Cout < "inserts an element into the queue header. PS: This is a backward push effect. If the previous queue is full, the last element will be moved out. " << endl;
C_usrdata data5 = {5, 5.55};
cb.push_front(data5);
DispCirBuff(cb);
//Prediction: at this time, the data in the queue should be: data5 data2 data3
Cout < "insert an element to the end of the queue, PS: This is the effect of pushing forward. If the queue is full before, the first element will be moved out. " << endl;
C_usrdata data6 = {6, 6.66};
cb.push_back(data6);
DispCirBuff(cb);
//Prediction: at this time, the data in the queue should be: data2 data3 data6
Cout < "remove last element in buffer" < endl;
cb.pop_back();
DispCirBuff(cb);
cout << cb.size() << endl << endl;
//Prediction: at this time, the data in the queue should be: data2 data3
Cout < "remove the first element in the buffer" < endl < < endl;
cb.pop_front();
DispCirBuff(cb);
cout << cb.size() << endl << endl;
//Prediction: at this time, the data in the queue should be: data2
return 0;
}
makefile:
.PHONY: DOIT
DOIT:
mips-linux-gnu-g++ -I. my_boost_test.cpp -L./lib -lboost_thread -lboost_system -o boost_app -lrt -lpthread
The results of measurement and experiment are all correct.
.