3

I am reading a code sample from cppreference:

#include <functional>
#include <queue>
#include <vector>
#include <iostream>

template<typename T> void print_queue(T& q) {
    while(!q.empty()) {
        std::cout << q.top() << " ";
        q.pop();
    }
    std::cout << '\n';
}

int main() {
    std::priority_queue<int> q;

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q.push(n);

    print_queue(q);

    std::priority_queue<int, std::vector<int>, std::greater<int> > q2;

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q2.push(n);

    print_queue(q2);

    // 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);

    for(int n : {1,8,5,6,3,4,0,9,7,2})
        q3.push(n);

    print_queue(q3);

}

I am not sure why q2 does not need to be initialized? I.e. Instead of having

std::priority_queue<int, std::vector<int>, std::greater<int> > q2;

in the original code, I guess we should have something like

std::priority_queue<int, std::vector<int>, std::greater<int> > q2(std::greater<int>());

So why when we have an customized compare function, we can omit the initializer for q2 but not for q3 in the code sample?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Sean
  • 2,649
  • 3
  • 21
  • 27

3 Answers3

10

The key difference is that std::greater is default constructible, but closure types (lambdas) are not.

Thus, the queue needs to be given a lambda object to copy construct its comparator from as a constructor argument.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
6

So why when we have an customized compare function, we can omit the initializer for q2 but not for q3 in the code sample

You have a "customized compare function" in both cases. Both std::greater<int> and decltype(cmp)> name the type of a function object. The difference between them is that std::greater<int> is default constructible while a lambda's type never is. So when initializing the priority queue, this constructor...

explicit priority_queue( const Compare& compare = Compare(),
                         Container&& cont = Container() );

... will (conceptually) happily default initialize std::greater<int>() but will fail on decltype(cmp)(). So you need to provide the later for copying explicitly.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458
2

This is the constructor which is being used in your case

explicit priority_queue( const Compare& compare = Compare(),
                     Container&& cont = Container() );

So if you don't pass any argument default constructors for the template classes will be called. But the decltype(cmp) is not default constructible. A lambda closure type has deleted default constructor. So you need to explicitly mention cmp().

In C++20, we will get these default constructors back. lambdas

nishantsingh
  • 4,537
  • 5
  • 25
  • 51