遊戲開發中頻繁需快速查找鍵值對應資料結構。THashedStringList(位於 IniFiles 單元)提供 O(1) 平均查找複雜度的雜湊表實作,適合鍵為字串、值為物件/指標的場景。
type
RTest = record
Key: Integer;
Name: string[20];
Sex: Boolean;
Age: Integer;
end;
PTest = ^RTest;
ScHash := THashedStringList.Create;
var
Index: Integer;
p_Test: PTest;
begin
Index := ScHash.IndexOf(IntToStr(p_Test.Key));
if Index = -1 then
ScHash.AddObject(IntToStr(p_Test.Key), TObject(Integer(p_Test)));
先以 IndexOf 檢查鍵是否存在(-1 表不存在),再以 AddObject 存入指標(轉型為 TObject)。
var
Index: Integer;
t_Object: TObject;
begin
Index := ScHash.IndexOf(IntToStr(p_Test.Key));
if Index <> -1 then begin
t_Object := ScHash.Objects[Index]; // 可取出指標進一步處理(如釋放記憶體)
ScHash.Delete(Index);
end;
end;
ScHash.Free;
同 TStringList,釋放容器本身;若 Objects 持有動態配置記憶體,需在 Delete 或 Clear 前手動釋放。
THashedStringList 內部維護雜湊桶陣列,Add/IndexOf/Delete 平均 O(1)。Values[Key]。Capacity 減少重新配置開銷。