user2558887
user2558887

Reputation:

C++11 why require comparing information twice for priority_queue construction

I feel dumb to ask this question, but I really want to know the reason before I seriously "type twice" in my future code.

For example, I construct an absolute max priority_queue from myVector (a vector defined before the code):

auto comp = []( int a, int b ) { return abs(a) < abs(b); };
priority_queue<int, vector<int>, decltype(comp)> pq(comp, myVector);

The comp lambda is required to fill in template (which I agree, because this priority_queue instance will has that order attribute in its life), and also required in constructor (which confuses me).

Why can not the constructor deduce the order based from the order information in template?

Upvotes: 0

Views: 67

Answers (1)

philsumuru
philsumuru

Reputation: 234

The C++ language stipulates that lambdas have deleted default constructors which means lambdas cannot be default-constructed. Thus code like this will not compile:

auto f1 = [](int i){return i;};
decltype(f1) f2; // ERROR: try to default-construct a lambda object "f2"

Given the implementation details of priority_queue below:

template<
     typename _ElemTy,
     typename _Container = vector<_ElemTy>,
     typename _Pred = less<typename _Container::value_type>
    >
    class priority_queue
    {
       priority_queue()
         : c(), comp() // use empty container, DEFAULT comparator
       {
       }

       priority_queue(const _Pred& p, const _Container& c)
          : cont(c), comp(p)
       {
          make_heap(cont.begin(), cont.end(), comp);
       }

       .....

if its default constructor is to be used and type _Pred is a lambda, expression comp() must cause a compile error. Thus you must use the second constructor above, which needs an explicitly provided lambda object.

Upvotes: 1

Related Questions