I'm working with a priority_queue in C++ and encountered a problem when using a static member function as a custom comparator within a class.
A reproducible example will be:
#include <bits/stdc++.h>
using namespace std;
class testClass {
private:
static bool comp(const int& a, const int& b) {
return a > b;
}
priority_queue<int, vector<int>, decltype(&testClass::comp)> q;
public:
void push(int num) {
q.push(num);
}
};
int main() {
testClass t;
t.push(0);
t.push(0);
return 0;
}
The second call to push
causes the error. I think this means the member function comp
cannot be called by q
.
However, when I change the member function to a lambda function outside the class and then reference it with decltype(comp)
, the code works fine.
Can someone explain why the static member function causes this issue, and why the lambda approach works instead?
The issue is not that you use the static member function as a comparator. The issue is that you don't use it.
std::priority_queue<int, vector<int>, decltype(&comp)> q;
The comparator is not passes to the constructor and one default constructed is used (null).
You should pass the comparator to the constructor
std::priority_queue<int, vector<int>, decltype(&comp)> q{comp};
I bet a duplicated question must be on SO, but I cannot find it.