Alright, so you have a TObjectList instance. You want to loop through the items in it and delete some of the objects from the list. You can't do this:
for I := 0 to ObjectList.Count - 1 do
if TMyClass(ObjectList[I]).ShouldRemove then
ObjectList.Delete(I);
...because once you delete the first object the index counter I will be all wrong and the loop won't work any more.
So here is my solution:
Again:
for I := 0 to ObjectList.Count - 1 do
if TMyClass(ObjectList[I]).ShouldRemove then
begin
ObjectList.Delete(I);
goto Again;
end;
This is the best solution I've found to this so far. If anyone has a neater solution I'd love to see it.
ObjectList[k]
has complexity O(k) (whenObjectList
is a list)? In this case, your algorithm has the wrong complexity to start with. If you are handling lists, you should have the proper operations on lists and not be writingfor
loops, and then you would not be wondering aboutgoto
(although you may be wondering about exceptions). – Pascal CuoqObjectList[k]
has complexity O(k) (and I suspect it has), your implementation language is forcing you to write algorithms with the wrong complexity. It's time to switch... There are languages in which you can remove elements you ShouldRemove from a list in O(length). – Pascal Cuoq