On goodliffe.net

Further afield

C++ circular buffer library

This is a simple C++ library (supplied entirely in one header file) that provides an STL-compliant circular buffer class.

Whilst it's entirely useful in it's own right, and will work predictably with the standard C++ alogrithms, it has also been the basis of a couple of Overload articles on writing STL-style template container classes. (See the publications page for information on these articles).

Compatibility

 The circular buffer class is not at all platform specific. All that is required to compile it is a sufficiently standards complient compiler. It has been built on the following compilers:

  • gcc 2.95.3 - gcc 4
  • Microsoft Visual C++ 6.0

Download

 The current code version is 1.0. It is available in the following source file: circular-1.0.tar.gz

Example of use

So how do you use this little puppy? Its hardly rocket science. Here's some example code to show you it in action.

int main()
{
    // create a circular buffer of ints with capacity 20
    circular_buffer cbuf(20);

    // Add 15 elements
    for (int n = 0; n < 15; ++n) cbuf.push_back(n*2);

    // Copy them to cout
    std::copy(cbuf.begin(), cbuf.end(), std::ostream_iterator(std::cout));

    // Add 10 more elements
    for (int n = 0; n < 10; ++n) cbuf.push_back(n*2);

    // Note now that 5 elements will have been consumed from the back of the buffer,
    // replaced by new data!

    // Print and consume each element
    while (!cbuf.empty())
    {
        std::cout << "element:" << cbuf.front();
        pop_front();
    }

    // done
    return 0;
}