简体   繁体   English

从STL优先级队列创建最小堆

[英]Creating Min Heap from STL Priority Queue

I am creating a min heap from stl priority queue. 我正在从stl优先级队列创建一个最小堆。 Here is my class which I am using. 这是我正在使用的课程。

class Plane
{
  private :
    int id ;
    int fuel ;
 public:
    Plane():id(0), fuel(0){}
    Plane(const int _id, const int _fuel):id(_id), fuel(_fuel) {}

    bool operator > (const Plane &obj)
    {
        return ( this->fuel > obj.fuel ? true : false ) ;
    }

} ; };

In main I instantiate an object thus. 在main中,我实例化了一个对象。

 priority_queue<Plane*, vector<Plane*>, Plane> pq1 ;
 pq1.push(new Plane(0, 0)) ;

I am getting an error from xutility which I am unable to understand. 我从xutility收到错误,我无法理解。

d:\\microsoft visual studio 10.0\\vc\\include\\xutility(674): error C2064: term does not evaluate to a function taking 2 arguments d:\\ microsoft visual studio 10.0 \\ vc \\ include \\ xutility(674):错误C2064:term不评估为带有2个参数的函数

Any help to its solution would be appreciated. 任何对其解决方案的帮助将不胜感激。

If you drop the use of pointers (which are overkill for your simple structures), then you can use std::greater from the header functional : 如果你放弃了指针的使用(这对你的简单结构来说是过度杀伤),那么你可以使用标头functional std::greater

std::priority_queue<Plane, std::vector<Plane>, std::greater<Plane> > pq1;
pq1.push(Plane(0, 0));

Currently, you are feeding Plane as the comparison type. 目前,您正在将Plane作为比较类型。 That won't work since the comparison type must be a type of function object, ie it must have an operator() that does the comparison. 这不起作用,因为比较类型必须是一种函数对象,即它必须有一个operator()来进行比较。 Plane doesn't have such a member (and adding it just for this purpose would be a bad idea). Plane没有这样的成员(并且仅为此目的添加它将是一个坏主意)。

std::greater has the appropriate method, implemented in terms of your operator> . std::greater具有适当的方法,根据您的operator> However, it doesn't work with pointers, because then it uses a pointer comparison (based on memory addresses). 但是,它不适用于指针,因为它使用指针比较(基于内存地址)。

Btw., note that your comparison function can be expressed more succinctly as 顺便说一句,请注意您的比较功能可以更简洁地表达为

bool operator>(const Plane &other)
{
    return fuel > other.fuel;
}

The third template parameter must be a binary functor taking teo Plane* . 第三个模板参数必须是采用teo Plane*的二元仿函数。 Your Plane class does not provide that. 你的Plane课没有提供。

You need something of the form 你需要一些形式的东西

struct CompPlanePtrs
{
  bool operator()(const Plane* lhs, const Plane* rhs) const {
    return lhs->fuel > rhs->fuel ;
  }
};

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

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