Boost C++ Libraries of the most highly regarded and expertly designed C++ library projects in the world. Herb Sutter and Andrei Alexandrescu, C++ Coding Standards

This is the documentation for an old version of Boost. Click here to view this page for the latest version.

Storage in containers

Suppose you want to ask users to choose some number (an int). One of the valid responses is to choose nothing, which is represented by an uninitialized optional<int>. You want to make a histogram showing how many times each choice was made. You can use an std::map:

std::map<boost::optional<int>, int> choices;

for (int i = 0; i < LIMIT; ++i) {
  boost::optional<int> choice = readChoice();

This works because optional<T> is LessThanComparable whenever T is LessThanComparable. In this case the state of being uninitialized is treated as a yet another value of T, which is compared less than any value of T.