I'm trying to declare a priority_queue of nodes
, using bool Compare(Node a, Node b)
as the comparator function (which is outside the node class).
What I currently have is:
priority_queue<Node, vector<Node>, Compare> openSet;
For some reason, I'm getting Error: "Compare" is not a type name
Changing the declaration to priority_queue <Node, vector<Node>, bool Compare>
gives me Error: expected a '>'
I've also tried:
priority_queue<Node, vector<Node>, Compare()> openSet;
priority_queue<Node, vector<Node>, bool Compare()> openSet;
priority_queue<Node, vector<Node>, Compare<Node, Node>> openSet;
How should I correctly declare my priority_queue
?
You should declare a class Compare
and overload operator()
for it like this:
class Foo
{
};
class Compare
{
public:
bool operator() (Foo, Foo)
{
return true;
}
};
int main()
{
std::priority_queue<Foo, std::vector<Foo>, Compare> pq;
return 0;
}
Or, if you for some reasons can't make it as class, you could use std::function
for it:
class Foo
{
};
bool Compare(Foo, Foo)
{
return true;
}
int main()
{
std::priority_queue<Foo, std::vector<Foo>, std::function<bool(Foo, Foo)>> pq(Compare);
return 0;
}
The third template parameter must be a class who has operator()(Node,Node)
overloaded.
So you will have to create a class this way:
class ComparisonClass {
bool operator() (Node, Node) {
//comparison code here
}
};
And then you will use this class as the third template parameter like this:
priority_queue<Node, vector<Node>, ComparisonClass> q;
The accepted answer makes you believe that you must use a class or a std::function
as comparator. This is not true! cute_ptr's answer showed how to pass a function to the constructor, but there's a simpler way:
priority_queue<Node, vector<Node>, decltype(&Compare)> openSet(Compare);
That is, there is no need to explicitly encode the function's type, you can let the compiler do that for you.
Answering your question directly:
I'm trying to declare a
priority_queue
of nodes, usingbool Compare(Node a, Node b) as the comparator function
What I currently have is:
priority_queue<Node, vector<Node>, Compare> openSet;
For some reason, I'm getting Error:
"Compare" is not a type name
The compiler is telling you exactly what's wrong: Compare
is not a type name, but an instance of a function that takes two Nodes
and returns a bool
.
What you need is to specify the function pointer type:std::priority_queue<Node, std::vector<Node>, bool (*)(Node, Node)> openSet(Compare)
One can also use a lambda function.
auto Compare = [](Node &a, Node &b) { //compare };
std::priority_queue<Node, std::vector<Node>, decltype(Compare)> openset(Compare);
来源:https://stackoverflow.com/questions/16111337/declaring-a-priority-queue-in-c-with-a-custom-comparator