The C++Course provides a general introduction to programming in C++. It is based on A.B. Downey's book, How to Think Like a Computer Scientist. Click here for details. |
![]() |
Home ![]() ![]() |
||
![]() ![]() ![]() ![]() ![]() ![]() |
||
The Golfer Class
As an example of something with an unusual definition of "highest" priority, we'll use golfers: class Golfer {public: pstring name; int score; Golfer (pstring name, int score) { this->name = name; this->score = score; } }
Since priority queues require some comparisons, we'll have to write a function compareTo. So let's write one: int compareTo (Golfer g1, Golfer g2) {int a = g1.score; int b = g2.score; // for golfers, low is good! if (a<b) return 1; if (a>b) return -1; return 0; } Finally, we can create some golfers: Golfer* tiger = new Golfer ("Tiger Woods", 61);Golfer* phil = new Golfer ("Phil Mickelson", 72); Golfer* hal = new Golfer ("Hal Sutton", 69); And put them in the queue: pq.insert (tiger);pq.insert (phil); pq.insert (hal); When we pull them out: while (!pq.empty ()) {golfer = pq.remove (); cout << golfer->name << ' ' << golfer->score; } They appear in descending order (for golfers): Tiger Woods 61Hal Sutton 69 Phil Mickelson 72 Ok, so now that we've got a priority queue done for golfers...FORE!!!
|
||
Home ![]() ![]() |