2022-02-02 10:44:02 -08:00
[#tutorial]
= Tutorial
:idprefix: tutorial_
2022-02-02 11:14:05 -08:00
2022-02-08 12:02:15 -08:00
When using a hash index with link:../../../multi_index/index.html[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 <<custom,section on extending boost::hash for a custom data type>>.
2022-02-02 11:14:05 -08:00
2022-02-08 11:53:30 -08:00
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:
2022-02-02 11:14:05 -08:00
2022-02-08 12:00:47 -08:00
[source]
2022-02-02 11:14:05 -08:00
----
2022-02-08 11:53:30 -08:00
std::unordered_multiset<int, boost::hash<int> >
2022-02-02 11:14:05 -08:00
set_of_ints;
2022-02-08 11:53:30 -08:00
std::unordered_set<std::pair<int, int>, boost::hash<std::pair<int, int> > >
2022-02-02 11:14:05 -08:00
set_of_pairs;
2022-02-08 11:53:30 -08:00
std::unordered_map<int, std::string, boost::hash<int> > map_int_to_string;
2022-02-02 11:14:05 -08:00
----
2022-02-08 11:53:30 -08:00
To use `boost::hash` directly, create an instance and call it as a function:
2022-02-02 11:14:05 -08:00
2022-02-08 12:00:47 -08:00
[source]
2022-02-02 11:14:05 -08:00
----
2022-02-08 11:53:30 -08:00
#include <boost/container_hash/hash.hpp>
2022-02-02 11:14:05 -08:00
int main()
{
2022-02-08 11:53:30 -08:00
boost::hash<std::string> string_hash;
2022-02-02 11:14:05 -08:00
std::size_t h = string_hash("Hash me");
}
----
For an example of generic use, here is a function to generate a vector containing the hashes of the elements of a container:
2022-02-08 12:00:47 -08:00
[source]
2022-02-02 11:14:05 -08:00
----
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::back_inserter(hashes),
2022-02-08 11:53:30 -08:00
boost::hash<typename Container::value_type>());
2022-02-02 11:14:05 -08:00
return hashes;
}
----