如何为队列重载>运算符

har*_*hit 1 c++

我有一个优先级队列,我已经定义如下:

priority_queue<Node*,vector<Node*>,greater<Node*>> myQueue; 
Run Code Online (Sandbox Code Playgroud)

我必须在参数参数的基础上添加到队列,我已经像这样重载它

bool Node::operator>(const Node& right) const
{   
    return param>right.param;
}
Run Code Online (Sandbox Code Playgroud)

由于重载函数不会占用指针对象,我应该如何更改它以便调用我的重载函数.我正在以这种方式添加队列:

Node *myNode
myQueue.add(myNode);
Run Code Online (Sandbox Code Playgroud)

我不能通过myNode而不作为指针对象.请指导..

@Sellibitze我做过这样的事情

    template<typename Node, typename Cmp = std::greater<Node> >
struct deref_compare : std::binary_function<Node*,Node*,bool>
{
    deref_compare(Cmp const& cmp = Cmp())
    : cmp(cmp) {}

    bool operator()(Node* a, Node* b) const {
        return cmp(*a,*b);
    }

private:
    Cmp cmp;
};

typedef deref_compare<Node,std::greater<Node> > my_comparator_t;
priority_queue<Node*,vector<Node*>,my_comparator_t> open; 
Run Code Online (Sandbox Code Playgroud)

我充满了错误.

sel*_*tze 7

您需要编写自己的仿函数进行比较,因为您不能重载operator> for pointers.因此,您将使用适当的函数调用运算符来使用您自己的专用类,而不是更大.这甚至可以一般地完成.

template<typename T, typename Cmp = std::less<T> >
struct deref_compare : std::binary_function<T const*,T const*,bool>
{
    deref_compare(Cmp const& cmp = Cmp())
    : cmp(cmp) {}

    bool operator()(T const* a, T const* b) const {
        return cmp(*a,*b);
    }
private:
    Cmp cmp;
};

typedef deref_compare<Node,std::greater<Node> > my_comparator_t;
Run Code Online (Sandbox Code Playgroud)

Edit1:我刚刚意识到你可以通过迭代器而不是指针来普遍地做到这一点.;-)

编辑2:如果你对模板不熟悉并且不需要这种概括,你也可以使用

struct my_node_ptr_compare
{
    bool operator()(Node const* a, Node const* b) const {
        return *a > *b;
    }
};

priority_queue<Node*,vector<Node*>,my_node_ptr_compare> foo;
Run Code Online (Sandbox Code Playgroud)