Home > Frameworks > boost::array

boost::array

This is another easy Boost class to tackle.  The C++ STL provides a plethora of specialized collection containers, all of them respecting a strict access interface that let them interact with common algorithms.  The problem is, there’s no direct substitute to the plain old, static C array.  The closest STL relative would be the std::vector, but it is implemented to allow dynamic sizing, which means some overhead unnecessary to handle plain statically sized arrays.

The boost::array allows just that: using C arrays the same way one would use an STL collection container, with services like iterators, swap(), size(), etc.  It also provides asserting when out-of-bound accesses through the operator[] occurs.

There is no constructor for the array, but they can be initialized like normal C arrays using the = {} nomenclature.  If the number of initial values is less than the size of the array, the remaining values are initialized to their default constructions.  If no = {} initialization is provided, all values are undefined (same as with C arrays).

And that’s pretty much what there is to it.  Here’s a simple example:

#include <boost/array.hpp>
// ...

boost::array<string,12> a = { "A", "B", "C" };

for(boost::array<string,4>::iterator iter(a.begin()); iter != a.end(); ++iter)
{
    cout << iter->c_str() << "\n";

    // This will assert:
    cout << a[25] << "\n";
}

– Steve

Advertisements
  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: