How do i remove items from a TArray while iterating?

Hey there, traditionally you could achieve this by iterating the array backwards (starting at the end) and removing as you go. If you wanted a more semantic solution you could try one of the following (I’ve used the example of removing all nullptrs):

TArray<FBla*> A;

with a lambda predicate:

A.RemoveAll([](const FBla* Ptr){
    return Ptr == nullptr;
}); 

If you didn’t mind allocating a new array, you could do this in one line:

auto FilteredArray = A.FilterByPredicate([](const FBla* Ptr){
    return Ptr != nullptr;
}); 

The other way is to iterate the array backwards, but this is generally not as clear as the previous two methods:

for (int32 Index = A.Num()-1; Index >= 0; --Index)
{
    if (A[Index] == nullptr)
    {
        const bool bAllowShrinking = false;
        A.RemoveAt(Index, 1, bAllowShrinking);
    }
}
2 Likes