www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Use classes as keys in associative array

reply JN <666total wp.pl> writes:
Is it possible to use different class instances as keys for 
associative array, but compare them by the contents? I tried to 
override opEquals but it doesn't seem to work. Basically I'd like 
this code to work. I know structs would work but I can't use 
structs for this):

import std.stdio;

class Name
{
     string s;

     this(string s)
     {
         this.s = s;
     }
}

void main()
{
     Name n1 = new Name("John");
     Name n2 = new Name("John");

     int[Name] ages;
     ages[n1] = 50;

     assert(ages[n2] == 50);
}
Jun 06 2020
next sibling parent ag0aep6g <anonymous example.com> writes:
On Saturday, 6 June 2020 at 16:49:29 UTC, JN wrote:
 Is it possible to use different class instances as keys for 
 associative array, but compare them by the contents? I tried to 
 override opEquals but it doesn't seem to work.
You also need toHash. https://dlang.org/spec/hash-map.html#using_classes_as_key
Jun 06 2020
prev sibling parent reply ikod <geller.garry gmail.com> writes:
On Saturday, 6 June 2020 at 16:49:29 UTC, JN wrote:
 Is it possible to use different class instances as keys for 
 associative array, but compare them by the contents? I tried to 
 override opEquals but it doesn't seem to work. Basically I'd
May be wrong, but probably you have to override opEquals to Object, not to another class instance.
Jun 06 2020
parent ikod <geller.garry gmail.com> writes:
On Saturday, 6 June 2020 at 20:31:36 UTC, ikod wrote:
 On Saturday, 6 June 2020 at 16:49:29 UTC, JN wrote:
 Is it possible to use different class instances as keys for 
 associative array, but compare them by the contents? I tried 
 to override opEquals but it doesn't seem to work. Basically I'd
May be wrong, but probably you have to override opEquals to Object, not to another class instance.
Oops, sorry, it was answered already
Jun 06 2020