Chapter 15. Boost.Unordered
Example 15.1. Using boost::unordered_set
boost::unordered_set
can be replaced with std::unordered_set
in Example 15.1. boost::unordered_set
doesn’t differ from std::unordered_set
.
Example 15.2. Using boost::unordered_map
Example 15.3. User-defined type with Boost.Unordered
In elements of type animal
are stored in a container of type boost::unordered_set
. Because the hash function of boost::unordered_set
doesn’t know the class animal
, hash values can’t be automatically calculated for elements of this type. That’s why a hash function must be defined – otherwise the example can’t be compiled.
The name of the hash function to define is hash_value()
. It must expect as its sole parameter an object of the type the hash value should be calculated for. The type of the return value of hash_value()
must be std::size_t
.
Usually, the definition of hash_value()
is rather simple: Hash values are created by accessing the member variables of an object one after another. This is done with the function boost::hash_combine()
, which is provided by Boost.Hash and defined in boost/functional/hash.hpp
. You don’t have to include this header file if you use Boost.Unordered because all containers from this library access Boost.Hash to calculate hash values.
In addition to defining hash_value()
, you need to make sure two objects can be compared using ==
. That’s why the operator operator==
is overloaded for animal
in Example 15.3.
The hash containers from the C++11 standard library use a hash function from the header file functional
. The hash containers from Boost.Unordered expect the hash function hash_value()
. Whether you use Boost.Hash within hash_value()
doesn’t matter. Boost.Hash makes sense because functions like make it easier to calculate hash values from multiple member variables step by step. However, this is only an implementation detail of hash_value()
. Apart from the different hash functions used, the hash containers from Boost.Unordered and the standard library are basically equivalent.