Exercise at end of Ch. 56 of "Programming in D"

Ali Çehreli acehreli at yahoo.com
Mon Aug 15 02:59:59 UTC 2022


On 8/14/22 19:23, Ali Çehreli wrote:

 >      // BUG DUE TO WISHFUL THINKING:
 >      override size_t toHash() const {
 >        /* Since the 'points' member is an array, we can take
 >         * advantage of the existing toHash algorithm for
 >         * array types. */
 >        return typeid(points).getHash(&points);

Thinking more about this, I think the above would still work if the 
Point type had a toHash() function that also ignored the color member. 
Adding just the following function makes the code work:

class Point {
   int x;
   int y;
   Color color;

   // ...

   override size_t toHash() const {
     return x + y;
   }
}

The book is simply forgetting to show that function. (Otherwise, I never 
put any code without testing.)

WARNING: Hash functions can be very tricky. I have a strong feeling that 
adding two integers is not an efficient one.

Ali



More information about the Digitalmars-d-learn mailing list