Pages

boost::circular_buffer

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;

namespace
{
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)
{
cb.push_back(i);

cout << i << ' ';
if(cb.full())
cout << "buffer full" << endl;
else
cout << "there is still room in the buffer" << endl;
}

dump(cb);

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

No comments:

Post a Comment