Analogue of priority queue

Hi,

There isn’t a direct analogue to std::priority_queue, but you can use heap functions on TArray instead, with an inverted predicate:

struct MyType
{
    explicit MyType(int32 InPriority);

    int32 Priority;
};

struct MyTypePredicate
{
    bool operator()(const MyType& A, const MyType& B) const
    {
        // Inverted compared to std::priority_queue - higher priorities float to the top
        return A.Priority > B.Priority;
    }
};

TArray<MyType> Queue;
Queue.HeapPush(MyType(10), MyTypePredicate());
Queue.HeapPush(MyType(5),  MyTypePredicate());
Queue.HeapPush(MyType(20), MyTypePredicate());
Queue.HeapPush(MyType(15), MyTypePredicate());

MyType Next;
Queue.HeapPop(Next, MyTypePredicate());
check(Next.Priority == 20);

Hope this helps,

Steve

4 Likes