Is there a HashSet in Delphi?

泪湿孤枕 提交于 2019-11-30 08:29:25

The standard collections do not offer a generic set class. Third party collections libraries such as Spring4D do.

You can build a generic set class quite easily on top of TDictionary<K, V>. A bare bones version might look like this:

type
  TSet<T> = class
  private
    FDict: TDictionary<T, Integer>;
  public
    constructor Create;
    destructor Destroy; override;
    function Contains(const Value: T): Boolean;
    procedure Include(const Value: T);
    procedure Exclude(const Value: T);
  end;

....

constructor TSet<T>.Create;
begin
  inherited;
  FDict := TDictionary<T, Integer>.Create;
end;

destructor TSet<T>.Destroy;
begin
  FDict.Free;
  inherited;
end;

function TSet<T>.Contains(const Value: T): Boolean;
begin
  Result := FDict.ContainsKey(Value);
end;

procedure TSet<T>.Include(const Value: T);
begin
  FDict.AddOrSetValue(Value, 0);
end;

procedure TSet<T>.Exclude(const Value: T);
begin
  FDict.Remove(Value);
end;

I've not compiled this code, so you may need to fix any mistakes I made. You'll likely want to extend it to be more capable. But hopefully this can show you how to start.

You can use TDictionary for that. Define the TKey type parameter to be the thing you want to track. The TValue type parameter can be anything; you won't be using it. (Perl also lacks a set type, and so convention is to use its hash type in the same manner I'm suggesting here.)

Call ContainsKey to check membership. Use Add or AddOrSetValue to insert; Remove to delete.

It would be a trivial exercise to write a wrapper that hides the unused TValue parameter.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!