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

时间:2012-12-07 15:00:08

标签: 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 ) ;
    }

};

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

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

我收到xutility的错误,我无法理解。

  

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

对此解决方案的任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:12)

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

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

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

std::greater有适当的方法,根据您的operator>实施。但是,它不适用于指针,因为它使用指针比较(基于内存地址)。

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

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

答案 1 :(得分:7)

第三个模板参数必须是采用teo Plane*的二元仿函数。您的Plane课程没有提供。

你需要一些形式

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