本文介绍了使用自定义比较器在c ++中声明priority_queue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图使用 bool比较(节点a,节点b)声明一个优先级节点作为比较器函数(它在节点类之外)。

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).

我目前拥有的是:

priority_queue<Node, vector<Node>, Compare> openSet;

出于某种原因,我得到错误:比较类型名称

For some reason, I'm getting Error: "Compare" is not a type name

将声明更改为 priority_queue< Node,vector< Node> ;, bool Compare& code>

Changing the declaration to priority_queue <Node, vector<Node>, bool Compare>

给我错误:预期a>'

我也尝试过:

priority_queue<Node, vector<Node>, Compare()> openSet;
priority_queue<Node, vector<Node>, bool Compare()> openSet;
priority_queue<Node, vector<Node>, Compare<Node, Node>> openSet; 

如何正确声明我的 priority_queue ?

推荐答案

您应该声明一个类比较和重载 operator(),如下所示:

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

或者,如果由于某些原因不能作为类,可以使用 std :: function :

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

这篇关于使用自定义比较器在c ++中声明priority_queue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-31 16:10