Comparator for Priority Queue[C++]

Viewed 226

I am trying to understand what my comparator should return for a Priority Queue of vectors where I want a min-heap based on third element.

On searching , I found out that the comparator looks like :

bool operator()(vector<int>a, vector<int> b)
{
return a[2]>b[2];
}

Why not a[2]<b[2]?

1 Answers

A max heap is a vector or binary tree where the data contained in each node is greater than or equal to that of its children, so the leaves have the smallest values in the queue. Internally, the priority queue is represented as a max heap and sorted so that nodes with the largest value can be accessed first. If you wanted to sort elements a[2]<b[2], you can overwrite the comparator.

Related