/********************************************************************************** *** FILE: deque_sample.cpp *** DATE: 02/09/2004 *** AUTHOR: Daniel Dementiev *** GOAL: Illustrate how to create a simple priority queue of class pointers *** using the deque container from STL. *** Please notice several things: *** - we need to define the < (less than) operator for the Robot class *** to be able to compare robots by their priority *** - we need to create a special class PRobot that contains nothing but *** a pointer to a robot. This is done exclusively to be able to define *** a comparison operator < (less than) for robot pointers. *** - inside the PRobot class we also redefine the type conversion operator *** Robot*() that allows us to conside any object of the PRobot class as *** a simple pointer to an object of the class Robot. **********************************************************************************/ #include #include #include using namespace std; class Robot{ private: int priority; public: Robot() : priority(rand()%25+1) {}; int getPr() { return priority; }; friend bool operator<(const Robot &a, const Robot &b); }; bool operator<(const Robot &a, const Robot &b) { return a.priority > b.priority; } class PRobot { private: Robot *robot_pointer; public: PRobot() : robot_pointer(NULL) {}; PRobot(Robot *robot) : robot_pointer(robot) {}; operator Robot*() const { return robot_pointer; }; friend bool operator<(const PRobot &a, const PRobot &b); }; bool operator<(const PRobot &a, const PRobot &b) { return *a.robot_pointer < *b.robot_pointer; } void main() { int i, j; deque pq; Robot *tank; for(i=0;i<15;i++){ tank = new Robot(); pq.push_back(tank); cout<<"Inserted tank with priority "<getPr()<<" into the array\n"; } sort(pq.begin(), pq.end()); cout<<"\nAfter sorting teh array is:\n"; while( ! pq.empty() ){ tank = pq.front(); cout<getPr()<<" "; pq.pop_front(); } }