如何重载>运算符作为队列 [英] how to overload > operator for a queue

查看:142
本文介绍了如何重载>运算符作为队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个优先级队列,我已经这样定义:

i have a priority queue and i have defined like this:

priority_queue<Node*,vector<Node*>,greater<Node*>> myQueue;

我必须添加到队列基于参数param和我已经重载它像这样

i have to add to queue on the basis of a parameter param and i have overloaded it like this

bool Node::operator>(const Node& right) const
{   
    return param>right.param;
}

因为重载函数不接受指针对象,我的重载函数被调用。
我以如下方式添加队列:

since the overload function doesnt take a pointer object, how should i change it so that my overloaded function is called. i am adding to queue this way:

Node *myNode
myQueue.add(myNode);

我不能传递myNode而不作为指针对象。
请指导..

i cant pass the myNode without making as pointer object. please guide ..

@Sellibitze
i做了这样的事情

@Sellibitze i have done something like this

    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;

我填满了错误。

推荐答案

您需要为比较编写自己的函子,因为你不能重载operator> for pointers。所以,而不是更大,你将使用自己的专用类与适当的函数调用操作符。

You need to write your own functor for the comparison because you can't overload operator> for pointers. So, instead of greater you would be using your own dedicated class with the appropriate function call operator. This could be even done generically.

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;

Edit1:我只是意识到你甚至可以迭代器而不是指针。 ; - )

I just realized you could do it even more generically, with iterators instead of pointers. ;-)

Edit2:如果你不习惯模板,不需要这个泛化,你也可以使用

If you're not comfortable with the template and don't need this generalization you could just as well use

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;

这篇关于如何重载&gt;运算符作为队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆