It works because Remove does shrink the array, I see you step back after removal so the next iteration would arrive at the next index. Perfectly valid way of doing it, just personally confusing for me to read as a potential team member. If you’re doing it this way rather than in reverse because you want to iterate in order, I’d recommend another approach:
TSet<TWeakPtr<AActor>> ActorsToRemove;
for (TWeakPtr<AActor>& Actor : OriginalArray)
{
if (bWantToRemove)
{
// This should be a ref (&) because the ptr object itself
// would be different if we made a copy
// and therefore calling remove with the copy
// object would not remove the original
ActorsToRemove.Add(Actor);
}
}
// Again, use a ref (&) to avoid making a copy because copied ptr is not
// the same as the original and Remove removes an item by its reference.
for (TWeakPtr<AActor>& Actor : ActorsToRemove)
{
OriginalArray.Remove(Actor);
}
ActorsToRemove.Empty();
Using the above solution probably seems like needless extra steps, but it also allows you to use a range-based iteration on your original array instead of creating a for loop with an index. That means your original array can actually be a set instead, which is much faster to iterate on and remove from than an array. This of course assumes that your original array’s order doesn’t matter. If it does, then use the array.