Let’s say we have a priority_queue that holds a bunch of ListNode objects declared as below:
class ListNode {
int val;
ListNode *next;
public:
explicit ListNode(int v) : val(v), next(NULL) {}
inline bool operator<(const ListNode& rhs) const {
return val < rhs.val;
}
};
std::priority_queue<ListNode> pq;
By overriding operator< method or providing a sorting functor we can have the priority_queue hold the ListNode objects in val’s ascending order.
My question is if the priority_queue holds the pointers to ListNode class instead can I have the pointers sorted so that the val’s pointed are in ascending order. How do I do that?
std::priority_queue<ListNode *> pq1;
Thanks!
As you said,
std::priority_queueaccepts as third template parameter a comparison functor that it has to use to perform the comparisons.Just write your own that dereferences the items before comparing them: