Building an unordered map with tuples as keys

前端 未结 6 1006
南方客
南方客 2021-02-01 05:40

In a C++ program with Boost, I am trying to build an unordered map whose keys are tuples of doubles:

typedef boost::tuples::tuple

        
6条回答
  •  独厮守ぢ
    2021-02-01 05:56

    Actually, you could perfectly define a general hash function for boost::tuple. The only requirement is that it lives within the same namespace so that it is picked up by ADL.

    I am actually surprised that they did not already write one.

    namespace boost { namespace tuples {
    
      namespace detail {
    
        template ::value - 1>
        struct HashValueImpl
        {
          static void apply(size_t& seed, Tuple const& tuple)
          {
            HashValueImpl::apply(seed, tuple);
            boost::hash_combine(seed, tuple.get());
          }
        };
    
        template 
        struct HashValueImpl
        {
          static void apply(size_t& seed, Tuple const& tuple)
          {
            boost::hash_combine(seed, tuple.get<0>());
          }
        };
      } // namespace detail
    
      template 
      size_t hash_value(Tuple const& tuple)
      {
        size_t seed = 0;
        detail::HashValueImpl::apply(seed, tuple);
        return seed;
      }
    
    } }
    

    Note: I have only proved it correct, I haven't tested it.

提交回复
热议问题