Recent

Author Topic: Associative arrays with a class type as key  (Read 4983 times)

simone

  • Sr. Member
  • ****
  • Posts: 260
Associative arrays with a class type as key
« on: August 17, 2018, 12:48:58 pm »
Sometimes I need to implement associative arrays. For this purpose, as far as I know, I should use TFPGMap available in FGL unit or TDictionary present in rtl-generics unit. However I noticed that TFPGMap does not allow TKey to be a class in the pair <TKey,TValue>. Did I understand correctly? Thanks in advance for responses.

LemonParty

  • New Member
  • *
  • Posts: 28
Re: Associative arrays with a class type as key
« Reply #1 on: August 17, 2018, 02:22:43 pm »
You can use this construction if the type of values is the same:
Code: Pascal  [Select]
  1. type
  2.  TKeys = (apple,orange,banana);
  3.  TAsArray = array[TKeys]of String;
  4. var A: TAsArray;
  5. begin
  6.  A[apple]:= '1';
  7.  A[banana]:= 'monkey';
  8.  Writeln(A[apple],A[banana]);
  9.  readln;
  10. end.
  11.  

Thaddy

  • Hero Member
  • *****
  • Posts: 9293
Re: Associative arrays with a class type as key
« Reply #2 on: August 17, 2018, 03:33:30 pm »
You mean:
Code: Pascal  [Select]
  1. {$ifdef fpc}{$mode delphi}{$H+}{$endif}
  2. uses generics.collections;
  3. type TMyClassMap = TObjectDictionary<Tobject, string>; // a map is a dictionary!
  4. var
  5.   map:TMyClassmap;
  6. begin
  7.   map := TMyClassmap.Create([doOwnsKeys, doOwnsValues]);    
  8.   try
  9.     //
  10.   finally
  11.     map.free;
  12.   end;    
  13. end.
That would be possible in  fgl too, but there you need to overload some operators, so it is more work.

« Last Edit: August 17, 2018, 03:48:02 pm by Thaddy »
also related to equus asinus.

simone

  • Sr. Member
  • ****
  • Posts: 260
Re: Associative arrays with a class type as key
« Reply #3 on: August 17, 2018, 05:11:16 pm »
Thanks Thaddy. In the past I used rtl-generics as in your example, for associative arrays/maps/dictionaries. Although rtl-generics is better than FGL, I generally tend to use the latter as it is part of the standard distribution of Lazarus. I hope in the future also rtl-generics will be included.

Thaddy

  • Hero Member
  • *****
  • Posts: 9293
Re: Associative arrays with a class type as key
« Reply #4 on: August 17, 2018, 05:30:50 pm »
rtl-generics is already in trunk. for 3.0.4. the OPM has a version.
also related to equus asinus.

simone

  • Sr. Member
  • ****
  • Posts: 260
Re: Associative arrays with a class type as key
« Reply #5 on: August 17, 2018, 06:29:48 pm »
This is good news. Thanks for the update.