首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> Delphi

Delphi 高效資料檢索:THashedStringList 實作 Hash 表完整指南

     編輯:Delphi

應用場景

遊戲開發中頻繁需快速查找鍵值對應資料結構。THashedStringList(位於 IniFiles 單元)提供 O(1) 平均查找複雜度的雜湊表實作,適合鍵為字串、值為物件/指標的場景。

核心操作範例

資料結構定義

type
  RTest = record
    Key: Integer;
    Name: string[20];
    Sex: Boolean;
    Age: Integer;
  end;
  PTest = ^RTest;

1. 建立雜湊表

ScHash := THashedStringList.Create;

2. 新增/更新資料

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)。

3. 刪除指定鍵

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;

4. 釋放雜湊表

ScHash.Free;

同 TStringList,釋放容器本身;若 Objects 持有動態配置記憶體,需在 Delete 或 Clear 前手動釋放。

進階提示

  • THashedStringList 內部維護雜湊桶陣列,Add/IndexOf/Delete 平均 O(1)。
  • 鍵值皆為字串時,可直接存取 Values[Key]。
  • 大量資料建議預設 Capacity 減少重新配置開銷。
  • 執行緒不安全,多執行緒環境需自行加鎖。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved