Simple question regarding dynamic arrays.

I am slightly confused about how removing an unit in the middle of the array and how it affects the array while its processing in a loop.

For example I have to loop through the array and delete few things in the middle of the array.

I loop through the array like this and matching certain conditions


for (int16 ActorIndex = 0; ActorIndex < AIgnoreActor.Num(); ActorIndex++)
{
        if (AIgnoreActor[ActorIndex] = ..........)
        {
                 ...........
                 ...........
        }
        else
        {
                AIgnoreActor.RemoveAt(ActorIndex);
         }
}

So if I remove an actor in the middle of a dynamic array, the next stored digit comes one step backwards to the present index of the deleted actor.
So, when index increases in the next iteration, wont the loop skip one index?

Also there is a method to remove without shrinking the array



SpawnArray.RemoveAt(k, 1,false);

Can this help?

There are a couple different options you could take. An easy one would be to iterate the loop in reverse. If you start from the end, when you remove the item, the next time you go through the loop, the counter will decrement and not be affected. Another option would be to only increment your counter when you don’t perform a removal. Finally, another option you could do (if you’re just looping to remove things that meet some condition) is to use the version of RemoveAll on TArray that is expecting a predicate. The syntax is a little bit funky, but it would look something like this (saving you from writing the loop at all):


AIgnoreActor.RemoveAll(](AActor* CurActor)
{
   // Write code in here that returns true if you want to remove CurActor and false if you do not. So you can check whatever condition you want to remove based on inside here.
   // As an example, if you wanted to remove an actor if it was NULL or the bHidden variable on it was true, you might do this:
   return (!CurActor || CurActor->bHidden); 
});

In this example, I’m assuming your array is an array of AActor*. If it’s not, you’d change the parameter type after the ] part. This will handle the loop for you, removing all of the elements in the array that return true from that code snippet.

Thanks… I used the first method. Such an easy way to do it. No idea why it didn’t think of it.

I have other functioning to do before removing so the .RemoveAll is not appropriate for this work…