TArray RemoveAll equivalent elements?

I have a TArray of structs and need to randomly pick an element i and then remove all elements for which the element == Array[i]

I wrote an overload for my struct’s == operator before realizing that both RemoveAll functions require a predicate.

How would I write a predicate to work like this, if possible?

(Also what is the best markdown for posting code)

Something like this?

for(auto it=MyArray.CreateIterator(); it; ++it) {
    if(element == *it) {
        MyArray.RemoveAt(it.GetIndex());
    }
}

edit: You can actually just use Remove.

MyArray.Remove(Element);

The name is kind of deceiving in my opinion. Makes it seem like it will remove only one item that matches and that RemoveAll is more appropriate, but indeed it will remove all items that match. It uses the == operator to check if they match. There’s also RemoveSingle to remove the first item it finds.

If you don’t care to preserve the order then RemoveSwap and RemoveSingleSwap is a faster option.

Predicate

The TArray::RemoveAll requires a predicate which just needs to be a callable type with one of these signatures:

bool (ArrayElementType)
bool (ArrayElementType&)
bool (const ArrayElementType&)

This means you can use a function, lambda, or a functor!

This is almost exactly what I eventually did except I tend to iterate over arrays using an index, is there an advantage to using an iterator?

I didn’t actually use either in this scenario. I did
While(MyArray.Find(Element, OutIndex))
{MyArray.RemoveAt(OutIndex);}
which might be pretty inefficient now that I’ve thought about it.

Actually it looks like you could just use Remove. Updated answer to reflect that.