2013-02-20 41 views
0

我的问题是:priority_queue声明和布尔运算符<声明

  • 我有我的计划有2类加为主;

  • 我已经在一个类的成员函数中声明了一个priority_queue;

  • 我必须定义的比较,我想我应该使用的代码是:

    // Determine priority (in the priority queue) 
    bool operator < (const node & a, const node & b) 
    { 
        return a.getPriority() > b.getPriority(); 
    } 
    

问:我应该在哪里插入这段代码?有人能帮助我吗?

谢谢

+0

为什么不让它成为'node'的成员函数? – jrok 2013-02-20 13:58:29

+0

,因为我得到一个错误:函数“运算符”的参数太多 – user1783116 2013-02-20 14:05:19

+1

成员运算符函数只能带1个参数:'bool operator <(const node&other){return this-> priority jrok 2013-02-20 14:07:52

回答

1

看起来你的operator<可能是node的一个不好的补充。问问自己:节点在逻辑上是否可比?是否清楚比较节点(priorty_queue的上下文之外)应该比较它们的优先级?也许它应该比较它们的位置或其他可能包含的内容。如果您提供operator<,则让其他5个比较运算符也是有意义的。如果不清楚node < node实际比较的是什么,请不要为节点提供operator<。在这样的情况下,最好提供自定义比较的priority_queue ...

struct NodeComparer 
{ 
    bool operator()(const node& left, const node& right) 
    { 
     return left.GetPriority() > right.GetPriority(); 
    } 
} 

...

std::priority_queue<node, std::vector<node>, NodeComparer> nodeQueue; 

这样你priority_queue可以作为期望的,但你不加不合逻辑的功能到node

+0

好吧,我明白你的意思。问题依然存在:我在A类的成员函数中有一个优先级队列,并且我已经分别定义了一个类“节点”。我在哪里插入你的代码? – user1783116 2013-02-20 14:20:52

+0

我把结构放在包含使用pq的成员函数的类的上面....现在它似乎工作!感谢您的建议 – user1783116 2013-02-20 14:28:36

+0

@ user1783116您也可以将包含'priority_queue'的类嵌套为private,因为它是该类的实现细节。 – David 2013-02-20 14:41:16

0

在声明priority_queue的位置应该看到此运算符。由于优先级队列仅存在于成员中,因此我会将运算符的定义置于实现该方法的.cpp文件中给定方法定义的上方。

+0

是的,你是对的。实际的问题是“node”是一个类,“A-star”是另一个类,其中我有成员函数,我已经使用了priority_queue。我能怎么做? – user1783116 2013-02-20 14:08:25