Home > Software engineering >  Why C returns error when I use my custom constructor in priority queue?
Why C returns error when I use my custom constructor in priority queue?

Time:12-07

priority_queue<pair<int, int>, vector<pair<int, int>>, comparator> pq;

static bool comparator(pair<int, int> &m, pair<int, int> &n) {
    if (m.second < n.second) return true;
    else return false;
}

Error: Error image

I defined my comparator inside a class, and try to declare the priority queue inside another function in the same class, and the error happens.

CodePudding user response:

The third template parameter to std::priority_queue is a type.

comparator is not a type. It is a function.

But before you can fix this, there are two more problems to fix:

  1. types and object must be declared before they are used, and the shown code does not declare comparator before using it.

  2. comparators must taken their parameters as const references, they are not allowed to modify them.

Therefore, your comparator should be:

static bool comparator(const pair<int, int> &m, const pair<int, int> &n)

Its type is: bool (*)(const pair<int, int> &, const pair<int, int> &)

That's what the third parameter to std::priority_queue template should be, and then the actual comparator must be passed to the object's constructor, std::priority_queue has an overloaded constructor that takes an instance of the comparator as a parameter:

static bool comparator(const pair<int, int> &m, const pair<int, int> &n) {
    if (m.second < n.second) return true;
    else return false;
}

priority_queue<pair<int, int>, vector<pair<int, int>>,
           bool (*)(const pair<int, int> &, const pair<int, int> &)
           > pq{comparator};

However, you will discover that most of this is unnecessary, and I showed it only for pedanticty's purposes. std::priority_queue's default comparator template parameter will work just fine, because std::pair implements operator<:

priority_queue<pair<int, int>, vector<pair<int, int>>> pq{comparator};

CodePudding user response:

The third template argument for template type parameter must be a type, whereas comparator is a function. You may get the type of the function with decltype(&comparator).

std::priority_queue<std::pair<int, int>, std::vector<std::pair<int, int>>, decltype(&comparator)> pq(comparator);

The last cppreference example with lambda is very similar to your code https://coliru.stacked-crooked.com/view?id=86f63b09847ba22e.

  • Related