Autor Beitrag
invarbrass
Hält's aus hier
Beiträge: 4



BeitragVerfasst: Di 29.04.08 06:47 
I have a snippet of code that iterates through a TList and deletes some items. The code is as follows:
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
procedure PurgeList;
var
  P: PSomeRecord;
  I: Integer;
begin
  I := 0;
  while (I < FList.Count) do  
  begin
    P := PSomeRecord(FList[I]);
    if P^.CanDelete then
    begin
      FreeMem(P);
      P := nil;
      FList.Delete(I);
      Continue;
    end;
    Inc(I);
  end;
end;

Is this the right way to delete items from a tlist? or will it enter into an infinite loop?
can anyone show me any other way to remove items from a tlist?
thanks in advance
hazard999
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Beiträge: 162

Win XP SP2
VS 2010 Ultimate, CC.Net, Unity, Pex, Moles, DevExpress eXpress App
BeitragVerfasst: Di 29.04.08 07:22 
Hi,

your source isn't wrong at all.

But you've to count downto 0.

If you're counting upwards you will leave every item after a delete untouched.

r u

René

_________________
MOV EAX, Result;MOV BYTE PTR [EAX], $B9;MOV ECX, M.Data;MOV DWORD PTR [EAX+$1], ECX;MOV BYTE PTR [EAX+$5], $5A;MOV BYTE PTR [EAX+$6], $51;MOV BYTE PTR [EAX+$7], $52;MOV BYTE PTR [EAX+$8], $B9;MOV ECX, M.Code;MOV DWORD PTR [EAX+$9], ECX


Zuletzt bearbeitet von hazard999 am Di 29.04.08 07:29, insgesamt 1-mal bearbeitet
Narses
ontopic starontopic starontopic starontopic starontopic starontopic starontopic starhalf ontopic star
Administrator
Beiträge: 10183
Erhaltene Danke: 1256

W10ent
TP3 .. D7pro .. D10.2CE
BeitragVerfasst: Di 29.04.08 07:24 
Hi!

I would suggest this:
ausblenden Delphi-Quelltext
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
procedure PurgeList;
  var
    P: PSomeRecord;
    i: Integer;
begin
  for i := FList.Count-1 downto 0 do begin
    P := PSomeRecord(FList.Items[i]);
    if (P^.CanDelete) then begin
      FreeMem(P);
      FList.Delete(i);
    end;
  end;
end;
cu
Narses

_________________
There are 10 types of people - those who understand binary and those who don´t.
invarbrass Threadstarter
Hält's aus hier
Beiträge: 4



BeitragVerfasst: Di 29.04.08 17:17 
thanks for the ideas. much appreciated. i've updated my code according to your suggestions. :D