简体   繁体   English

自定义类的STL优先级队列

[英]STL Priority Queue on custom class

I'm having a lot of trouble getting my priority queue to recognize which parameter it should sort by. 我在使用优先级队列来识别它应该排序的参数时遇到了很多麻烦。 I've overloaded the less than operator in my custom class but it doesn't seem to use it. 我在我的自定义类中重载了less运算符但它似乎没有使用它。 Here's the relevant code: 这是相关的代码:

Node.h Node.h

class Node
{   
public:
    Node(...);
    ~Node();
    bool operator<(Node &aNode);
...
}

Node.cpp Node.cpp

#include "Node.h"
bool Node::operator<(Node &aNode)
{
    return (this->getTotalCost() < aNode.getTotalCost());
}

getTotalCost() returns an int getTotalCost()返回一个int

main.cpp main.cpp中

priority_queue<Node*, vector<Node*>,less<vector<Node*>::value_type> > nodesToCheck;

What am I missing and/or doing wrong? 我错过了什么和/或做错了什么?

less<vector<Node*>::value_type> Means that your comparator compares the pointers to each other, meaning your vector will be sorted by the layout in memory of the nodes. less<vector<Node*>::value_type>表示比较器将指针相互比较,这意味着您的向量将按节点内存中的布局进行排序。

You want to do something like this: 你想做这样的事情:

#include <functional>
struct DereferenceCompareNode : public std::binary_function<Node*, Node*, bool>
{
    bool operator()(const Node* lhs, const Node* rhs) const
    {
        return lhs->getTotalCost() < rhs->getTotalCost();
    }
};

// later...
priority_queue<Node*, vector<Node*>, DereferenceCompareNode> nodesToCheck;

Note that you need to be const-correct in your definition of totalCost . 请注意,您需要在totalCost的定义中使用const-correct。

EDIT: Now that C++11 is here, you don't need to inherit from std::binary_function anymore (which means you don't need to #include functional) 编辑:既然C ++ 11在这里,你不再需要从std :: binary_function继承(这意味着你不需要#include功能)

You need to make your parameter const , because as of now you're giving it a non-cost reference, which means you might modify the object you're comparing with. 你需要设置你的参数const ,因为到目前为止你给它一个非成本参考,这意味着你可以修改你正在比较的对象。 (Which you aren't, and probably shouldn't). (你不是,也可能不应该)。

You're not being const-correct. 你不是正确的。 Your operator< doesn't make modifications to the Node, so the function should be const: 您的operator<不对节点进行修改,因此该函数应为const:

bool operator<(const Node &aNode) const;

After that, if you have trouble calling the getTotalCost() function, it's likely that it is not const as well. 之后,如果你在调用getTotalCost()函数时遇到问题,那么它很可能也不是const。 Mark it as const if it's not already: 如果它还没有,请将其标记为const:

int getTotalCost(void) const;

Your code is now (more) const-correct. 您的代码现在(更多)const-correct。

On a side note, binary operators are usually implemented outside the class: 另外,二元运算符通常在类外实现:

class Node
{
public:
    // ...

    int getTotalCost(void) const;

    // ...
};

bool operator<(const Node& lhs, const Node& rhs)
{
    return lhs.getTotalCost() < rhs.getTotalCost();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM