About the cmp in priority_queue

I want to define the cmp in priority_queue by myself, the code is as follows:
1
2
3
4
5
auto cmp = [](const ListNode* a, const ListNode* b)
	{
		return a->val > b->val;
	};
priority_queue < ListNode*, vector<ListNode*>, decltype(cmp)> minheap(cmp);

Why should I use decltype(cmp) and minheap(cmp) instead of just cmp and minheap()?
However, if I define the cmp use the code below:
1
2
3
4
5
6
7
struct cmp 
{
	bool operator() (ListNode* l1, ListNode* l2) 
	{
		return l1->val > l2->val;
	}
};

I can simply define the priority_queue as:
 
priority_queue < ListNode*, vector<ListNode*>, cmp> minheap();

It seems that the cmp parameter in priority is different from that in sort() function. I do not know the reason for it.
Thanks very much if you can help me.
> Why should I use decltype(cmp)

The type of cmp - the closure type of the lambda expression - is left to the implementation.
There is no other good way to specify its type.


> Why should I use minheap(cmp)

With C++20, where closure types without a capture have a defaulted default constructor, we can write:
std::priority_queue < ListNode*, std::vector<ListNode*>, decltype(cmp) > minheap ;

Prior to C++20, a closure type is not default constructible, we need to create it via a lambda expression and pass it to the constructor (it is a copyable object).
Topic archived. No new replies allowed.