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

Sas*_*sha 4 c++ priority-queue min-heap

我正在从stl优先级队列创建一个最小堆.这是我正在使用的课程.

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 ) ;
    }
Run Code Online (Sandbox Code Playgroud)

};

在main中,我实例化了一个对象.

 priority_queue<Plane*, vector<Plane*>, Plane> pq1 ;
 pq1.push(new Plane(0, 0)) ;
Run Code Online (Sandbox Code Playgroud)

我收到一个xutility我无法理解的错误.

d:\ microsoft visual studio 10.0\vc\include\xutility(674):错误C2064:term不评估为带有2个参数的函数

任何对其解决方案的帮助将不胜感激.

Fre*_*Foo 12

如果你放弃使用指针(这对你的简单结构来说是过度杀伤),那么你可以std::greater从标题中使用functional:

std::priority_queue<Plane, std::vector<Plane>, std::greater<Plane> > pq1;
pq1.push(Plane(0, 0));
Run Code Online (Sandbox Code Playgroud)

目前,您正在Plane作为比较类型.这不起作用,因为比较类型必须是一种函数对象,即它必须具有进行operator()比较的类型.Plane没有这样的成员(并且仅为此目的添加它将是一个坏主意).

std::greater有适当的方法,按照你的方式实施operator>.但是,它不适用于指针,因为它使用指针比较(基于内存地址).

顺便说一句,请注意您的比较功能可以更简洁地表达为

bool operator>(const Plane &other)
{
    return fuel > other.fuel;
}
Run Code Online (Sandbox Code Playgroud)


jua*_*nza 7

第三个模板参数必须是采用teo的二元仿函数Plane*.你的Plane班级没有提供.

你需要一些形式的东西

struct CompPlanePtrs
{
  bool operator()(const Plane* lhs, const Plane* rhs) const {
    return lhs->fuel > rhs->fuel ;
  }
};
Run Code Online (Sandbox Code Playgroud)