我正在尝试将用户定义的平面对象添加到优先级队列:
int main( )
{
std::string filename;
cout << "Enter file name >> ";
getline( cin, filename );
ifstream fin;
fin.open( filename.c_str( ) );
if( fin.fail( ) )
{
cout << "Unable to open the input file" << endl;
exit(1);
}
priority_queue<Plane*,vector<Plane*>,greater<Plane*> > pq;
Plane * p1;
while(fin)
{
fin.get( );
fin >> *p1;
pq.push(*p1);
}
Plane p;
int size=pq.size();
for(int i=0;i<3;i++)
{
p=pq.top();
cout<<i<<" "<<p;
pq.pop();
}
}
飞机级:
#include "plane.h"
Plane::Plane( )
{
flightNum = "Not set";
numOfPassengers = -1;
fuel = -1;
}
ostream& operator << ( ostream& os, const Plane& p )
{
os << "Flight Number: " << p.flightNum
<< "\nNumber of Passengers " << p.numOfPassengers
<< "\nRemaining fuel: " << p.fuel;
return os;
}
bool Plane::operator>( const Plane& p2) const
{
if(this->fuel>p2.getFuel())
{
return true;
}
else
{
return false;
}
}
ifstream& operator >> ( ifstream& fin, Plane& p )
{
fin>>p.flightNum;
fin>>p.numOfPassengers;
fin>>p.fuel;
}
我收到的错误是:
In function ‘int main()’:
welcome.cc:127: error: no matching function for call to ‘std::priority_queue<Plane*,
std::vector<Plane*, std::allocator<Plane*> >, std::greater<Plane*> >::push(Plane&)’
/usr/lib/gcc/i686-redhat-
linux/4.4.6/../../../../include/c++/4.4.6/bits/stl_queue.h:509: note: candidates are:
void std::priority_queue<_Tp, _Sequence, _Compare>::push(const typename _Sequence::value_type&) [with _Tp = Plane*, _Sequence = std::vector<Plane*, std::allocator<Plane*> >, _Compare = std::greater<Plane*>]
welcome.cc:151: error: no match for ‘operator=’ in ‘p = pq.std::priority_queue<_Tp, _Sequence, _Compare>::top [with _Tp = Plane*, _Sequence = std::vector<Plane*, std::allocator<Plane*> >, _Compare = std::greater<Plane*>]()’
程序的要求是它需要将平面对象添加到优先级队列。优先考虑的是飞机的燃料。
答案 0 :(得分:1)
第一个错误是因为您没有包含cstdlib头文件
第二,当你使用具有优先级队列的用户定义的类时,在这种情况下,容器应该如何比较你的新类型“飞机类”?因此,您应该重载小于(&lt;)运算符。
您已重载大于运算符(&gt;)