Reputation:
As per specification of priority queue
template<
class T,
class Container = std::vector<T>,
class Compare = std::less<typename Container::value_type>
> class priority_queue;
But why this odd syntax with Lambda?
// Using lambda to compare elements.
auto cmp = [](int left, int right) { return (left ^ 1) < (right ^ 1); };
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3(cmp);
Why we need to pass cmp as an argument?
Upvotes: 3
Views: 133
Reputation: 172894
Before C++20 lambda closure types are not DefaultConstructible; they have no default constructor. So you have to pass a lambda object to the constructor of std::priority_queue
. (Closure types have copy and move constructor.)
Copy-constructs the comparison functor
comp
with the contents ofcompare
. Value-initializes the underlying containerc
.
Since C++20 if no captures are specified, the closure type has a defaulted default constructor. Then you can construct std::priority_queue
without passing the lambda.
std::priority_queue<int, std::vector<int>, decltype(cmp)> q3;
Default constructor. Value-initializes the comparator and the underlying container.
Upvotes: 2