A circular buffer is quite a useful concept. It is not difficult to adapt a "normal" container to emulate it. Basically, when we are going forward and we reach its end we should just move back to the beginning.

But, as usual, it is not worthy to reinvent the wheel, if someone else it is providing it to us, it works, and it does what we are expecting from it.

This is the case of the circular buffer concept and its boost implementation boost::circular_buffer.

Here is a short example to show how it works:

#include <iostream>
#include "boost/circular_buffer.hpp"

using namespace std;

template <class T>
void dump(boost::circular_buffer<T>& buf)
copy(buf.begin(), buf.end(), ostream_iterator<T>(cout, " "));
cout << endl;

void cirbuf() {
const int BUF_SIZE = 3;
// Create a circular buffer with a capacity for 3 integers.
boost::circular_buffer<int> cb(BUF_SIZE);

// Insert some elements into the buffer.
for(int i = 0; i < BUF_SIZE; ++i)

cout << i << ' ';
cout << "buffer full" << endl;
cout << "there is still room in the buffer" << endl;


for(int i = 0; i < BUF_SIZE; ++i)
cout << cb.front() << ' ';
cout << "buffer empty" << endl;
cout << "there is still stuff in the buffer" << endl;

No comments:

Post a Comment