【问题标题】:Creating Min Heap from STL Priority Queue从 STL 优先级队列创建最小堆
【发布时间】:2012-12-07 15:00:07
【问题描述】:

我正在从 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): error C2064: term 不计算为采用 2 个参数的函数

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

【问题讨论】:

    标签: c++ priority-queue min-heap


    【解决方案1】:

    如果您放弃使用指针(这对于您的简单结构来说太过分了),那么您可以使用标题 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&gt; 实现。但是,它不适用于指针,因为它使用指针比较(基于内存地址)。

    顺便说一句,请注意,您的比较函数可以更简洁地表示为

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

    【讨论】:

    • 好的,但是为了得到我的支持,这个答案需要解释为什么元素类型是不合适的比较器类型,以及为什么 OP 的原始代码没有编译。 :-)
    • 它工作正常,但我无法理解其背后的原因,正如@Lightness Races in Orbit 提到的那样。
    • @larsmans 它怎么知道它必须根据我的燃料订购?
    • std::greater 将调用您的operator&gt;。它只知道这样做。
    • @LightnessRacesinOrbit:太糟糕了,您没有发现最严重的错误:std::greater 会进行指针比较。又改了答案。
    【解决方案2】:

    第三个模板参数必须是一个二进制函子,采用 teo Plane*。您的 Plane 类不提供。

    你需要某种形式的东西

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

    【讨论】:

    • 我不能用运算符 > 来做吗?交朋友? operator() 也不对。
    • @Sasha 问题是您需要将 pointersPlanes 进行比较,而不是 Planes。你不能为指针重载operator&gt;
    猜你喜欢
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-08
    • 2014-10-18
    • 2019-03-11
    • 2012-07-20
    • 1970-01-01
    相关资源
    最近更新 更多