4

I'd like use boost::unordered_map<key,value>, where key is a std::set<int>. Since a set of integers is no built-in type, I assumed I had to supply my own hash function (or, rather, I was thinking of using boost's hash_range).

However, now I tried initializing a hash map like this, neither supplying a hash function nor an equality predicate -- and gcc didn't complain. What is happening here? Is boost clever enough to hash STL containers all on its own? Is this going to be slower than if I used a custom hash function? What about using boost::hash_range?

Thanks in advance.

Egon
  • 317
  • 1
  • 3
  • 9
  • Did you actually link the entire program into an executable? – Kerrek SB Sep 17 '11 at 21:40
  • Yes, and it runs fine. Originally, I had used std::map (thinking I would take care of the hashing business later) and have now simply replaced it with unordered_map. – Egon Sep 17 '11 at 21:42
  • Oh, sorry, you're talking about the boost version, not the std version. Never mind. You could still use the std version and use the boost hasher if you like :-) – Kerrek SB Sep 17 '11 at 21:43

2 Answers2

3

According to the Boost documentation:

the default hash function is Boost.Hash

And, according to the documentation for Boost.Hash, default hash functions are provided for the standard containers. Consequently, there is already a hash function written for std::set. The Boost hash containers aren't smart enough to know how to hash sets automatically, but they are smart enough to use the implementation that's already provided.

Hope this helps!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
3

The default boost::hash< Key > function is being chosen. According to its documentation

As it is compliant with TR1, it will work with:

integers
floats
pointers
strings

It also implements the extension proposed by Peter Dimov in issue 6.18 of the Library Extension Technical Report Issues List (page 63), this adds support for:

arrays
std::pair
the standard containers.
extending boost::hash for custom types.

http://www.boost.org/doc/html/hash.html

So yes, boost is clever enough to hash STL containers. Unless you know something specific of your particular use case of set, I doubt there is any point in providing your own hash function.

K-ballo
  • 80,396
  • 20
  • 159
  • 169