Boost logo

Boost :

Subject: [boost] hash_combine vs hash_value
From: Michael Goldshteyn (mgoldshteyn_at_[hidden])
Date: 2011-03-25 09:57:38


After reading the explanation of how hash_combine should be used, I am left
wondering. Why is the recommendation for hash_combine different from what
one would intuitively expect?

Namely, given:

struct MyStruct
{
  int a;
  int b;
  int c;
};

The recommendation via examples and documentation is:

size_t hash(const MyStruct &s)
{
  size_t hashValue=0;

  // Combine hashes of all elements
  hash_combine(hashValue,s.a);
  hash_combine(hashValue,s.b);
  hash_combine(hashValue,s.c);

  return hashValue;
}

Rather than what I would think is the expected correct approach:

size_t hash(const MyStruct &s)
{
  // For a composite hash, start by hashing the first element
  size_t hashValue=hash_value(s.a);

  // Then, combine with hashes of the remaining elements
  hash_combine(hashValue,s.b);
  hash_combine(hashValue,s.c);

  return hashValue;
}

Thanks,

Michael Goldshteyn
 


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk