It is much easier to just call .Sort() on the variable holding the TArray. If you are using a custom data structure, be sure to overload the less than operator. Example of the syntax attached.
The way I did it was I created a static “predicate” function which returns a bool: whether the item should be sorted or not.
If you wanted to have a function that sorts items of the type AMyClass, you’d declare a public static function with a bool return type, like the following example (Since it’s static, the class you declare this function is up to you. For the sake of this example, I’ll be declaring it inside an imaginary AMyClass class):
Then, go to the respective *.cpp file and define the predicate function. This way of handling a sort is especially useful if you want to sort based on a particular variable from the class you’re passing in. For instance, lets say we had a class representing our character that holds multiple stats like speed, strength, etc… we could make a predicate function to sort an array by the speed stat, so that higher speed stats appear at the front of the array. The function should return true if the sort should occur (I believe, at least – someone please correct me if I’m wrong).
Your example in your question compiles fine for me in MSVC 2019.
For example
TArray<USceneComponent*> TheArray;
TheArray.Sort([](const USceneComponent& ip1, const USceneComponent& ip2) {
// access some random field just to test compile
return ip1.IsDeferringMovementUpdates() < ip2.IsDeferringMovementUpdates();
});
What error did you get? Did you include the file for OfClassPointers so that it’s defined wherever you are trying to sort by it?
I struggled a bit with this 2 and it only became clear after learning what predicates are.
I also wrote some tutorials/guides on how to work with the data structures for future reference…
There is a section like below you’ll be interested in
" In this example we are passing them in by reference because the TArray::Sort() function REQUIRES your predicate to take in references even if your TArray is made up of pointers.
So TArray<UApples*> will still require a predicate using UApples&…"