cedrusx
cedrusx

Reputation: 93

Why does this custom comparator fail in construcing std::priority_queue while it works for std::sort?

A comparator comp was defined as below. It works fine with std::sort, but fails to compile in the constructor of std::priority_queue. What is the problem? Thanks.

#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

bool comp(int a, int b) { return a > b; }

int main()
{
    vector<int> vec = {4, 2, 1, 3};
    sort(vec.begin(), vec.end(), comp); // OK
    priority_queue<int> q1(less<int>(), vec); // OK
    priority_queue<int> q2(comp, vec); // Fail
    return 0;
}

Error message:

error: no matching function for call to 'std::priority_queue<int>::priority_queue(bool (&)(int, int), std::vector<int>&)'
  priority_queue<int> q2(comp, vec);
                                  ^

Upvotes: 4

Views: 134

Answers (1)

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153955

The type of the default comparator of std::priority_queue is std::less<T> where T is the value type. You are passing something of type bool(*)(int, int) instead. std::sort() being a function can deduce the comparator's type. Class types can't deduce their template arguments (yet - there us discussion in the C++ committee that a future version may have class templates whose template arguments can be deduced.

You can use

std::priority_queue<int, std::vector<int>, bool(*)(int, int)> q(comp);

or, avoiding a hard-to-inline function pointer:

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

Upvotes: 7

Related Questions