I am trying to add a user-defined plane object to a priority queue:
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();
}
}
The plane-class:
#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;
}
The error I am receiving is:
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*>]()’
The requirement of the program is that it needs to add the plane object to the priority queue. The priority is the fuel of the plane.
The first error is because you didn’t include cstdlib header file
Second when you use a user defined class with a priority queue, how is the container supposed to compare your new type in this case “The plane class” ? Hence you should overload the less than (< ) operator.
You have overloaded the greater than operator ( > )