Storing class objects in a priority_queue. : Priority Queue « Data Structure « C++






Storing class objects in a priority_queue.

Storing class objects in a priority_queue.
#include <iostream>
#include <queue>
#include <string>
using namespace std;

class Thread {
  int priority;
  string name;
public:
  Thread() { 
     name = ""; 
     priority = 0; 
  }
  Thread(string n, int p) { 
     name = n; 
     priority = p; 
  }

  string getname() const { 
     return name; 
  }
  int getpriority() const { 
     return priority; 
  }
};

// Determine priority.
bool operator<(const Thread &a, const Thread &b)
{
  return a.getpriority() < b.getpriority();
}

int main()
{
  priority_queue<Thread> q;
  
  q.push(Thread("F", 10));
  q.push(Thread("M", 2));

  // show priority
  cout << "Priorities: "; 
  while(!q.empty()) {
    cout << q.top().getname() << endl;
    cout << "            ";
    q.pop();
  }

  return 0;
}


           
       








Related examples in the same category

1.Demonstrate a priority_queue.Demonstrate a priority_queue.
2.Using a different comparison function: greaterUsing a different comparison function: greater
3.PriorityQueue: push, pop and topPriorityQueue: push, pop and top