Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

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);
                                  ^
like image 370
cedrusx Avatar asked Mar 12 '23 03:03

cedrusx


1 Answers

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;
like image 152
Dietmar Kühl Avatar answered Apr 26 '23 16:04

Dietmar Kühl