How to order AActor by distance using TArray::Sort()?

Like this:

Array.Sort([](const ArrayType& LHS, const ArrayType& RHS)  { return LHS > RHS; });

ArrayType is type used in array, make code telling if left is bigger the the right and Sort function will sort items based of that.

Or if you have some specific base class which you want to be softed in specific way all you need to do is override < operator in it and you can use argument-less Sort function:

1 Like


Actually i’m looking for a clear example of the usage of TArray::Sort() with predicate class. In fact the predicate class is where i get lost. Basically i want to rearrange a TArray of actors from closer to far.

I’ve done this before using the bubble sort algorithm, but some people had told me is not the best way. So any help or example of how to use predicate class to TArray::Sort() will be great, even a simple example of how to arrange number from lower to higher will be awesome?

Thanks :slight_smile:

Sorry for my slow mind procces of things (for not say something uglier jejeje)What i dont get is where should i write this, is in .h or .cpp?. Also if the Array.Sort(), can be replaced with, egg: CollectedActors.Sort()?. And for array type, could i change it or use different types. egg: MyCharacter, MyActor, int32, float etc?

Thanks a lot i just do some thinking, and got it to work, is actually pretty simple, ill do the real thing tomowrrow cause im very tired. Just one last question: Is this more efficient and fastest than writing a “custom sort method” like bubble sort or quicksort?

I think that how to sort a TArray of FVectors based on Z attribute? (or X or Y) … and then, based on your answer, I found it:

TargetLocations.Sort([](const FVector& LHS, const FVector& RHS) { return LHS.Z > RHS.Z; });