Ying Xiong
Ying Xiong

Reputation: 4928

C++: How to compute hash value from several hashable members?

Suppose I have a C++ class

class T {
  Type1 member1;
  Type2 member2;
  Type3 member3;
  unsigned long hash() {
    // How to implement?
  }
};

Assuming each member hash a hash function member.hash(). What is the best way to implement the hash function of class T? Java has a HashCodeBuilder class specific for this task, is there a counterpart in C++?

I know one possible solution could be something like

member1.hash() + member2.hash() * 17 + member3.hash() * 37

Is this generally a good hash function? And how should I choose the constants 17, 37, etc., esp. if I more than 3 members?

Another minor question is assuming one of my member is primitive type (int, float, string, etc.), how should I generate a hash value from it?

Upvotes: 0

Views: 590

Answers (2)

Barry
Barry

Reputation: 302932

Boost has something for this: hash_combine

size_t seed = 0;
boost::hash_combine(seed, member1);
boost::hash_combine(seed, member2);
boost::hash_combine(seed, member3);
return seed;

Upvotes: 3

Slava
Slava

Reputation: 44248

If you use unordered containers from std you may consider the way as given on example in http://en.cppreference.com/w/cpp/utility/hash

std::size_t operator()(S const& s) const 
{
    std::size_t h1 = std::hash<std::string>()(s.first_name);
    std::size_t h2 = std::hash<std::string>()(s.last_name);
    return h1 ^ (h2 << 1);
}

Upvotes: 0

Related Questions