The Boost C++ Libraries

Chapter 20. Boost.Container

Boost.Container is a Boost library that provides the same containers as the standard library. Boost.Container focuses on additional flexibility. For example, all containers from this library can be used with Boost.Interprocess in shared memory – something that is not always possible with containers from the standard library.

Boost.Container provides additional advantages:

Example 20.1 illustrates incomplete types.


The examples in this chapters cannot be compiled with Visual C++ 2013 and Boost 1.55.0. This bug is described in ticket 9332. It was fixed in Boost 1.56.0.

Example 20.1. Recursive containers with Boost.Container
#include <boost/container/vector.hpp>

using namespace boost::container;

struct animal
  vector<animal> children;

int main()
  animal parent, child1, child2;

The class animal has a member variable children of type boost::container::vector<animal>. boost::container::vector is defined in the header file boost/container/vector.hpp. Thus, the type of the member variable children is based on the class animal, which defines the variable children. At this point, animal hasn’t been defined completely. While the standard doesn’t require containers from the standard library to support incomplete types, recursive containers are explicitly supported by Boost.Container. Whether containers defined by the standard library can be used recursively is implementation dependent.

Example 20.2. Using boost::container::stable_vector
#include <boost/container/stable_vector.hpp>
#include <iostream>

using namespace boost::container;

int main()
  stable_vector<int> v(2, 1);
  int &i = v[1];
  std::cout << i << '\n';

Boost.Container provides containers in addition to the well-known containers from the standard library. Example 20.2 introduces the container boost::container::stable_vector, which behaves similarly to std::vector, except that if boost::container::stable_vector is changed, all iterators and references to existing elements remain valid. This is possible because elements aren’t stored contiguously in boost::container::stable_vector. It is still possible to access elements with an index even though elements are not stored next to each other in memory.

Boost.Container guarantees that the reference i in Example 20.2 remains valid when the first element in the vector is erased. The example displays 1.

Please note that neither boost::container::stable_vector nor other containers from this library support C++11 initializer lists. In Example 20.2 v is initialized with two elements both set to 1.

boost::container::stable_vector is defined in boost/container/stable_vector.hpp.

Additional containers provided by Boost.Container are boost::container::flat_set, boost::container::flat_map, boost::container::slist, and boost::container::static_vector: