wupher
wupher

Reputation: 63

HashCodeBuilder in C++

If I want generate a hash for a given object in Java, the easiest way I know is to use the Apache Commons HashCodeBuilder:

public class Person {
   String name;
   int age;
   boolean smoker;
   ...

   public int hashCode() {
     // you pick a hard-coded, randomly chosen, non-zero, odd number
     // ideally different for each class
     return new HashCodeBuilder(17, 37).
       append(name).
       append(age).
       append(smoker).
       toHashCode();
   }
 }

Is there anything similar in C++?

Upvotes: 3

Views: 419

Answers (2)

John
John

Reputation: 1673

By the way, the hashCode method does not return an identifier for an object. This is a common misconception. There is nothing to prevent 2 objects of the same class returning the same value. The hashCode is meant for hash table data structures, not for identifying objects. Those are 2 separate concepts.

Upvotes: 0

Martin v. Löwis
Martin v. Löwis

Reputation: 127567

Use boost::hash_combine.

Upvotes: 7

Related Questions