Link to home
Create AccountLog in
Avatar of nikif
nikifFlag for Greece

asked on

Moving a list into another

Good morning,
could anyone help me in this?

In Delphi-6 I have a piece of code which declares
var MyList, TempList: TList;

MyList has some items. TempList has the same items in a different order. Both lists refer to pointers of the same type.
How can I move TempList to the var MyList? I do not wish to execute re-ordering directly in MyList since it might no be definitive.

When I assign
MyList := TempList;
all looks fine, although freeing lists produces following error
"Access violation at address [addr]. Read of address [addr]"

Thank you for the attention
Nikiforos
Avatar of MerijnB
MerijnB
Flag of Netherlands image

The reason you get the access violation, is (at least I assume) that you free TempList.
When you do MyList := TempList, both vars point to the same list, if you that list, both variables become invalid.

try something like:

var MyList: TList;
    TempList: TList;
    i: integer;
begin
 MyList := TList.Create();
 TempList := TList.Create();
 
 try
  // add your stuff to the lists
  
  
  // now we do the actual moving from TempList to MyList
  for i := 0 to TempList.Count - 1 do
   if MyList.IndexOf(TempList[i]) = -1 then  // check if MyList does not (already) contain this pointer in TempList
    MyList.Add(TempList[i]);                 // if not add it to MyList
	
  // now all pointers which were not (yet) in MyList were added from TempList
  // if you want to remove them from TempList call TempList.Clear();
  
  // TempList.Clear();  // uncomment this line if you want to remove the pointers from TempList
 finally
  MyList.Free();
  TempList.Free();
 end;
end;

Open in new window

Avatar of nikif

ASKER

Dear MerijnB thank you for your attention,

Unfortunately what you proposed does not work as I expected.
Let's say MyList contains items A-B-C-D-E-F-G
TempList contains items A-F-E-D-C-B-G

Your proposition copies all pointers to MyList, so in line 18 MyList comes with items A-B-C-D-E-F-G-A-F-E-D-C-B-G
My aim is MyList with items A-F-E-D-C-B-G

Thank you
Nikiforos
ASKER CERTIFIED SOLUTION
Avatar of MerijnB
MerijnB
Flag of Netherlands image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Avatar of nikif

ASKER

That's perfect
Thank you
Nikif
Avatar of nikif

ASKER

That's perfect

Thank you
Nikiforos