Home > Frameworks > boost::circular_buffer

boost::circular_buffer

The circular buffer is a simple container.  It always starts with a fixed size (pre-allocated) and if the container ever becomes full, adding new elements will simply overwrite the oldest ones.  So it’s perfectly fine to write into a circular buffer infinitely.

As the circular buffer respect the normal STL container interface, and how simple it is, I will not talk about it in length.  Here’s a little test code I did:

#include <boost/circular_buffer.hpp>

...

boost::circular_buffer<char> cb(10);

// Add test data in the buffer
const string kTestChar("Oh well, hello world!");
for(int i(0); i<(int)kTestChar.length(); i++)
{
    cb.push_back(kTestChar[i]);
}

// Retrieve data into a string
string newString;
for(boost::circular_buffer<char>::const_iterator iter(cb.begin()); iter != cb.end(); ++iter)
{
    newString.push_back(*iter);
}

// Output the result
cout << newString.c_str() << endl;

As expected, the output string will be “llo World!” as the circular buffer could only hold the last 10 pushed characters.

A few worthy notes:

  • The data type must support copy operation as the buffer never re-allocate any memory.  A new data overriding an old one is simply copied over.
  • It is possible to change the capacity of a circular buffer after its creation by using set_capacity.

 

Advertisements
Categories: Frameworks
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: