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?
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
compwith 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With