STL优先级队列在自定义类 [英] STL Priority Queue on custom class

查看:166
本文介绍了STL优先级队列在自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有很多麻烦让我的优先级队列识别应该排序哪个参数。我重载了我的自定义类中的less运算符,但它似乎并没有使用它。以下是相关代码:

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. Here's the relevant code:

Node.h

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

Node.cpp

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

getTotalCost()返回int

getTotalCost() returns an int

main.cpp

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

我失踪和/或做错了什么?

What am I missing and/or doing wrong?

推荐答案

更少< vector< Node *> :: value_type> 意味着比较器比较 / em>,这意味着你的向量将按照节点内存中的布局排序。

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.

你想这样做:

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


$ b 。

编辑:现在C ++ 11在这里,你不需要继承std :: binary_function不需要#include功能)

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)

这篇关于STL优先级队列在自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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