Skip to content

Instantly share code, notes, and snippets.

@SomethingWithComputers
Created January 12, 2021 00:36
Show Gist options
  • Save SomethingWithComputers/48e32b281d1bf8e662412e4113df43dc to your computer and use it in GitHub Desktop.
Save SomethingWithComputers/48e32b281d1bf8e662412e4113df43dc to your computer and use it in GitHub Desktop.
A simple Priority Queue (Binary Heap) wrapper for UE4's TArray (for example for A*/A star and Greedy graph traversal)
template <typename InElementType>
struct TPriorityQueueNode {
InElementType Element;
float Priority;
TPriorityQueueNode()
{
}
TPriorityQueueNode(InElementType InElement, float InPriority)
{
Element = InElement;
Priority = InPriority;
}
bool operator<(const TPriorityQueueNode<InElementType> Other) const
{
return Priority < Other.Priority;
}
};
template <typename InElementType>
class TPriorityQueue {
public:
TPriorityQueue()
{
Array.Heapify();
}
public:
// Always check if IsEmpty() before Pop-ing!
InElementType Pop()
{
TPriorityQueueNode<InElementType> Node;
Array.HeapPop(Node);
return Node.Element;
}
TPriorityQueueNode<InElementType> PopNode()
{
TPriorityQueueNode<InElementType> Node;
Array.HeapPop(Node);
return Node;
}
void Push(InElementType Element, float Priority)
{
Array.HeapPush(TPriorityQueueNode<InElementType>(Element, Priority));
}
bool IsEmpty() const
{
return Array.Num() == 0;
}
private:
TArray<TPriorityQueueNode<InElementType>> Array;
};
// -- Usage
// Lower number means higher priority
// -- Construction
TPriorityQueue<UTile*> Frontier;
// -- Adding elements: (element, priority)
Frontier.Push(TargetTile, 0.0f);
Frontier.Push(Grid->At(10, 16), 8.0f);
Frontier.Push(StartTile, 1000.0f);
// -- Iteration
while (!Frontier.IsEmpty()) {
UTile* Current = Frontier.Pop(); // Removes it from the top of the heap
Current->DoMagic();
}
@script526
Copy link

HeapPop/HeapPush don’t work with custom structs, right? It seems to expect some type of UObject in the Sorting.h

@SomethingWithComputers
Copy link
Author

Correct! The built-in TArray only works with UObjects. It's worth considering if you can refactor the custom structs you're using to something inheriting UObjects, the performance implications are quite minimal.

@script526
Copy link

Thanks. I was afraid about performance.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment