| Home | Libraries | People | FAQ | More

### 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();
      ++choices[choice];
    }

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`. `optional<T>` can also be stored as a key in `std::unordered_map` and `std::unordered_set` as it provides specializations for `std::hash`.