我需要存储未知数量的组。每个组都有未知数量的元素/项目。
这是我的“小组”:
TGroup= array of Integer; <------ dynamic array (as you can see) :)
我想使用 TList 来保存我的组。我的想法是,我可能想稍后访问这些组并向其中添加更多项目。
我有这段代码,但我无法让它工作:
TYPE
TGroup= array of Integer; // Each group has x items (x can be from 1 to 10000)
procedure TForm1.FormCreate(Sender: TObject);
VAR CurGroup: TGroup;
grp, item: Integer;
Groups: TList; // can contain up to 1 million groups
begin
Groups:= TList.Create;
{ Init }
for grp:= 1 to 4 DO // Put a dummy item in TList
begin
SetLength(CurGroup, 1); // Create new group
Groups.Add(@CurGroup); // Store it
end;
CurGroup:= NIL; // Prepare for next use
for grp:= 1 to 4 DO // We create 4 groups. Each group has 3 items
begin
CurGroup:= Groups[Groups.Count-1]; // We retrieve the current group from list in order to add more items to it
{ We add few items }
for item:= 0 to 2 DO
begin
SetLength(CurGroup, Length(CurGroup)+1); // reserve space for each new item added
CurGroup[item]:= Item;
end;
Groups[Groups.Count-1]:= @CurGroup; // We put the group back into the list
end;
{ Verify }
CurGroup:= NIL;
CurGroup:= Groups[0];
Assert(Length(CurGroup)> 0); // FAIL
if (CurGroup[0]= 0)
AND (CurGroup[1]= 1)
AND (CurGroup[2]= 2)
then Application.ProcessMessages;
FreeAndNil(Groups);
end;
注:代码已完成。您可以将其粘贴到您的 Delphi (7) 中进行尝试。
哦,这在较新版本的 Delphi 中会好得多...您可以使用通用的 TList。 var 组:TList;
最好的办法是使用另一个动态数组:Groups: array of TGroup;
原因是动态数组是由编译器管理和引用计数的。 TList 只对指针进行操作。当尝试将动态数组放入 TList 时,没有直接的方法可以保持引用计数正常。
您遇到的另一个问题是您要添加堆栈地址将动态数组变量添加到 TList,而不是实际数组。表达式 @CurGroup 是“CurGroup 变量的地址”,它是一个局部变量,位于堆栈上。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)