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.
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;
};