【发布时间】:2011-03-03 22:58:32
【问题描述】:
我需要存储未知数量的组。每个组都有未知数量的元素/项目。 这是我的“组”:
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) 中进行尝试。
【问题讨论】:
-
你所说的“组”是指具有同一元素的联合岩浆,并且每个元素都有一个逆元素?
-
@Andreas - 不。对我来说,该组只是一个数字列表(数组)。这是我对“组”的定义:TGroup= 整数数组;