0

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{
public:
    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.

1 Answer 1

3

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{
public:
    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
{
public:
    test()
        : test_pq(compare)
    {
        // Constructor code here
    }
private:
    priority_queue<int,vector<int>,comp> test_pq;
};
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for the through reply :) But isn't there a way to make it work irrespective of version? Say by shifting the initialisation to the class constructor?
@ant_1618, yes, of course you can do this. I updated answer to include this variant too. But if you already know words initialization and constructor I'd expect that you should already know an answer… =)
I wasnt aware of cpp's way of initialising member variables implicitly in the constructor with Test() : [initialisation list] { \\ code}. So, I couldnt have come up with this answer :P Now it is clear though :D Thank you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.