0

我想在 Delphi 中对两个值使用一个键,就像这样

TDictionary<tkey, tfirstvalue,tsecondvalue>;
4

3 回答 3

2

将您的价值观放入像记录一样的复合结构中。然后将该记录类型用作您的字典值类型。

于 2018-01-02T21:38:28.113 回答
1

Delphi 没有 Tuple 类型。我不知道您的目的,但记录类型的动态数组可能会有所帮助。

Type
Tdict_ = reocord
 tkey:integer;
tfirstvalue,Tsecondvalue :string;
end;
var
Tdict:array of tdict_
...
procedure adddata(Tkey:integer;tfirstvalue:string;Tsecondvalue :string); 
begin
     setlength(tdict,length(tdict)+1);
    tdict[length(tdict)-1].tkey:=tkey;
    tdict[length(tdict)-1].tfirstvalue:=tfirstvalue;
    tdict[length(tdict)-1].tsecondtvalue:=tsecondvalue;    
end;

但是您必须为数组的返回索引编写自己的“查找”函数。

例如

    Function find(tkey:integer):integer;
    var i:Integer;
    begin
     for i:=0 to length(Tdict)-1 do
     if tdict[i].tkey=i then
       begin
        result:=i;
        break;
       end;
    end;

    Function deletecalue(tkey:integer):integer;
    var i,j:Integer;
    begin
     i:=find(tkey)
        for j:=i to length(Tdict)-2 do
           tdict[j]:=tdict[j+1];
        setlength(tdict,length(tdict)-1);

    end;

如果键是字符串类型,则必须更改,但是对于大日期来说会很慢。

另请阅读: https ://github.com/malcolmgroves/generics.tuples

于 2018-01-03T11:27:55.440 回答
0

TDictionary<TKey, TPair<TFirstValue, TSecondValue>>, as @RudyVelthuis commented, is possible and works. However, TPair (found in System.Generics.Collections) is not meant for that - the two values are named Key and Value, which doesn't make sense here. We should make a copy of TPair, which could be named TTuple.

You can then do MyDictionary.Add('key', TTuple<string, string>.Create('firstvalue', 'secondvalue'));

Since it is implemented as a record (value type), there is no need to free it.

于 2020-01-29T17:08:17.663 回答