Delphiで連想配列

古いDelphiってMapクラスって用意されていないんですよね。僕の所有する最新のDelphiも2006です。

とはいえ、それ以前のDelphiでも「KeyがString型に限定される」ので良ければMapを使う事が出来ます。お馴染み、TStringListクラスですね。

とはいえ、TStringListをTMapとして使うにはちょっと機能不足です。自分で足りない部分を補ってやる必要があります。

TMap = class(TStringList)
public
  function Put(Key: String, Value: TObject): TObject;
  function Get(Key: TObject): TObject;
end;

function TMap.Put(Key: String, Value: TObject): TObject;
var
  Index: Integer;
begin
  Index := IndexOf(Key);
  if Index < 0 then
  begin
    result := nil;
    AddObject(Key, Value);
  end
  else begin
    result := Objects[Index];
    Objects[Index] := Value;
  end;
end;

function TMap.Get(Key: String): TObject;
var
  Index: Integer;
begin
  Index := IndexOf(Key);
  if Index < 0 then
    result := nil
  else
    result := Objects[Index];
end;

ただし、キーはリニアサーチなので、大量件数を登録するのは無理です。

それ以上の事をやりたければ、アルゴリズムの教科書でも読みながら自分で実装してください。

ではでは。