Trouble with pushing values into array

Hey there !

I have a class that looks like this:

class PATHING_API UPathNode : public UObject
{
	GENERATED_BODY()

public:

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category  = "Node Properties")
	int32 Hcost;

	UPROPERTY(EditAnywhere, BlueprintReadWrite, Category  = "Node Properties")
	int32 Fcost;

};

I need to sort the instances of this class by their Fcosts. I found that TArray can use
HeapPush and HeapPop. The documentaion says that < operator needs to be defined in the class so I tried to do something like this :

bool UPathNode::operator<(const UPathNode* Other)
{
	if(this->Fcost < Other->Fcost)
		return true;

	if(this->Fcost == Other->Fcost)
	{
		if(this->Hcost < Other->Hcost)
			return true;
	}

	return false;
}

But I got a error that says:
Sorting.h(38): [C2664] 'bool TLess<UPathNode *>::operator ()(const T &,const T &) const': cannot convert argument 1 from 'T' to 'const T &'

I don’t know how to fix this. I also looked at example on this page but couldn’t how quite figure out how to sort my class.

Could anybody please help me with this ?

Try this:

TArray<UPathNode*> PnArray;

PnArray.Sort([](const UPathNode& pn1, const UPathNode& pn2) {
	if(pn1.Fcost < pn2.Fcost)
		return true;

	if(pn1.Fcost == pn2.Fcost)
	{
		if(pn1.Hcost < pn2.Hcost)
			return true;
	}

	return false;
});
2 Likes

Thank you ! That fixed it for me.

1 Like