C++ Logo


Advanced search

Subject: std::hash (partial) specialization for std::tuple and std::pair?
From: Shachar Shemesh (shachar_at_[hidden])
Date: 2020-12-29 09:38:14

Hi all,

I often find is useful to create a hash table (sorry, "unordered_map")
with a key that is either a tuple or a pair. I found it highly
surprising that the default hash implementation does not offer
specialization to those types. This is especially true as writing one
myself did not turn out to be particularly difficult.

static constexpr size_t FibonacciHashMultiplier = 0x9e3779b97f4a7c15;
//static_cast<size_t>(-1) / GoldenRatio;

namespace std {

 Â Â Â  template<typename T1, typename T2>
 Â Â Â  struct hash< pair<T1, T2> > {
 Â Â Â Â Â Â Â  size_t operator()( const pair<T1, T2> &hashed ) const {
 Â Â Â Â Â Â Â Â Â Â Â  size_t result = std::hash<T1>()( hashed.first );
 Â Â Â Â Â Â Â Â Â Â Â  result *= FibonacciHashMultiplier;
 Â Â Â Â Â Â Â Â Â Â Â  result += std::hash<T2>()( hashed.second );

 Â Â Â Â Â Â Â Â Â Â Â  return result;
 Â Â Â Â Â Â Â  }
 Â Â Â  };

I think it is fairly obvious how that above can be extended to handling
std::tuple as well. Is there any reason I'm missing _not_ to include
this in the standard library?


STD-DISCUSSION list run by std-discussion-owner@lists.isocpp.org

Older Archives on Google Groups