我正在从 STL 优先级队列创建一个最小堆。这是我正在使用的类(class)。
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 does not evaluate to a function taking 2 arguments
对其解决方案的任何帮助将不胜感激。
最佳答案
如果您放弃使用指针(这对于您的简单结构来说太过分了),那么您可以使用 std::greater
来自标题 functional
:
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;
}
关于c++ - 从 STL 优先级队列创建最小堆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13765588/