How do I access the members of a TMap in a predicate for ValueSort()?

I am trying to sort a TMap of (int32, float) by smallest float to largest.

I have made a predicate function that I think ought to do that but I don’t know the syntax or how you access the members of the TMap via the predicate. I’d be happy with an inline solution I just thought making a function might be better. Also I notice there seems to be an “isless” function in the Unreal library but I don’t know how to pass arguments to it.

Would appreciate any help as I understand the concept of a predicate but I’m a bit stumped with how TMaps handle them.

1 Like

This will sort by smallest.

UFUNCTION(BlueprintCallable, Category = "ExBPFL")
	static void SortMapByFloat(const TMap<int32, float>& Src, TMap<int32, float>& outMap)
	{
		for (const TPair<int32, float>& entry : Src)
		{
			outMap.Add(entry);
		}

		outMap.ValueSort([](float s1, float s2)
		{
			return s1 < s2;
		});
	}

Take a look at @trdwll 's comment for an example using copying, but essentially the ValueSort function takes a function as an argument. The members of the TMap to be compared are passed as arguments to the predicate function.

This function takes two values and should return a boolean indicating whether the first parameter is less than the second parameter.

In your case, the code would be

TMap<int32, float> MyMap;

// Some code...

MyMap.ValueSort([](float A, float B)
{
    return A < B;
});

If you aren’t familiar with the [](float A, float B) syntax, this is a lambda/anonymous function. You can read a bit more here: Lambda expressions in C++ | Microsoft Docs

1 Like

Thank you, I have heard of lambdas but never used them. The time to start is now I suppose. Must predicates to functions like ValueSort always be passed in a lambda syntax?

They do not need to be lambdas, but I believe it is the easiest method.

In standard C++, the lambda syntax actually produces a class with an overloaded operator(). In this case you could add a

class FMyValueSort
{
    public:
        bool operator(float A, float B) const
        {
            return A < B;
        }
};

somewhere (either in your .cpp or .h file) and do your sorting like so

FMyValueSort MyValueSort;

MyMap.ValueSort(MyValueSort);

I think the lambda method is easier but I do like the look of passing a function like that for something I am using often. Thank you for the further enlightenment.