Search code examples
delphidelphi-5

Does Delphi 5 have a sorted dictionary container?


I'm new to Delphi 5 and looking for a container (ideally a built-in one) that will do the same job as map does in C++ (i.e. a sorted dictionary). I've done a preliminary Google search but nothing obvious seems to be suggesting itself. Please can anyone point me in the right direction?


Solution

  • This brings back memories. There is another interesting technique that's suitable for ancient versions of Delphi like yours. Read on!

    From your description you sound like you want a fairly generic container - ie, one you can use with a variety of types. This cries out for generics (yes, use a new Delphi!) But back in the old days, there used to be a slightly hacky way to implement templates / generics with Delphi pre-2009, using a series of defines and includes. It took a bit of googling, but here's an article on these 'generics' that's much like what I remember. It's from 2001; in those days Delphi 5 was still recent-ish.

    The rough idea is this: write a class to do what you want (here, a map from key to value) for a type, and get it working. Then change that file to use a specific name for the type (TMyType, anything really) and strip the file so it's no longer a valid unit, but contains code only. (I think two partial files, actually: one for the interface section, one for implementation.) Include the contents of the file using {$include ...}, so your whole Pascal file is compiled using your definitions and then the contents of the other partial included files which uses those definitions. Neat, hacky, ugly? I don't know, but it works :)

    The example article creates a typed object list (ie, a list not of TObject but TMemo, TButton, etc.) You end up with a file that looks like this (copied from the linked article):

    unit u_MemoList;
    
    interface
    
    uses
      Sysutils,
      Classes,
      Contnrs,
      StdCtrls;
    
    {$define TYPED_OBJECT_LIST_TEMPLATE}
    type
      _TYPED_OBJECT_LIST_ITEM_ = TMemo;
    {$INCLUDE 't_TypedObjectList.tpl'}
    
    type
      TMemoList = class(_TYPED_OBJECT_LIST_)
      end;
    
    implementation
    
    {$INCLUDE 't_TypedObjectList.tpl'}
    
    end.
    

    You will need to write your own map-like class, although you should be able to base it on this class. I remember that there used to be a set of 'generic' containers floating around the web which may have used this technique, and I would guess map is among them. I'm afraid I don't know where it is or who it was by, and Googling for this kind of thing shows lots of results for modern versions of Delphi. Writing your own might be best.

    Edit: I found the same article (same text & content) but better formatted on the Embarcadero Developer Network site.

    Good luck!