Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

priority queue with lambda syntax is confusing

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?


1 Answers

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 of compare. Value-initializes the underlying container c.

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.

like image 90
songyuanyao Avatar answered Jul 25 '26 14:07

songyuanyao



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!