ant_1618 ant_1618 - 1 year ago 153
C++ Question

Defining priority queue inside a class with a custom comparator function

I am trying to define a priority queue with custom comparator as follows:

typedef bool (*comp)(int,int);

bool compare(int exp1,int exp2){
return (exp1 > exp2);

class test{
priority_queue<int,vector<int>,comp> test_pq(compare); // Gives compilation error

int main ()
priority_queue<int,vector<int>,comp> pq(compare); // Compiles perfectly
return 0;

This is the compilation error that shows up

test.cpp:18:47: error: ‘compare’ is not a type
priority_queue<int,vector<int>,comp> test_pq(compare);

I have also tried declaring another compare function inside the test class with no effect. Why does the priority queue in the main function compile while the one inside the class doesnt? Is defining a dedicated class for comparator the only work around here?
Thank you.

Answer Source

Your code in test class tries to declare a method test_pq with incorrect signature.

To define member variable you can use curly braces in initialization (C++11 required):

class test{
    priority_queue<int,vector<int>,comp> test_pq{compare};

To achieve the same in pre C++11 you need to write custom constructor for test class:

class test{
    test(): test_pq(compare) {}
    priority_queue<int,vector<int>,comp> test_pq;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download