boost.png (6897 bytes) Home Libraries People FAQ More

PrevUpHomeNext

Tutorial

When using a hash index with Boost.MultiIndex, you don't need to do anything to use boost::hash as it uses it by default. To find out how to use a user-defined type, read the section on extending boost::hash for a custom data type.

If your standard library supplies its own implementation of the unordered associative containers and you wish to use boost::hash, just use an extra template parameter:

std::unordered_multiset<std::vector<int>, boost::hash<int> >
        set_of_ints;

std::unordered_set<std::pair<int, int>, boost::hash<std::pair<int, int> >
        set_of_pairs;

std::unordered_map<int, std::string, boost::hash<int> > map_int_to_string;

To use boost::hash directly, create an instance and call it as a function:

#include <boost/hash/hash.hpp>

int main()
{
    boost::hash<std::string> string_hash;

    std::size_t h = string_hash("Hash me");
}

If you wish to make use of the extensions, you will need to include the appropriate header (see the reference documentation for the full list).

#include <boost/hash/pair.hpp>

int main()
{
    boost::hash<std::pair<int, int> > pair_hash;

    std::size_t h = pair_hash(std::make_pair(1, 2));
}

Or alternatively, include <boost/hash.hpp> for the full library.

For an example of generic use, here is a function to generate a vector containing the hashes of the elements of a container:

template <class Container>
std::vector<std::size_t> get_hashes(Container const& x)
{
    std::vector<std::size_t> hashes;
    std::transform(x.begin(), x.end(), std::insert_iterator(hashes),
        boost::hash<typename Container::value_type>());

    return hashes;
}
Copyright © 2005 Daniel James

PrevUpHomeNext