David Yuan David Yuan - 5 months ago 59
C++ Question

Priority Queue with custom comparator

I am trying to use a priority queue to hold a custom objected with the following member variables:

class Jobs{
string id;
string location;
int start;
int end;

I will be reading from file a hashmap of Job ID and the weight of the job. I will ultimately have a

unordered_map<string, int> jobWeight;

holding this information. I want to push a list of Jobs into a priority_queue eventually with the priority based on the hashmap jobWeight. The highest weighted job should come first.

Referring to other tutorials, I noticed that you should create a separate class/struct and implement the operator(). Then you would pass in this comparison class into the priority_queue parameters. However, it appears that the priority_queue creates a new instance of this comparator class with default parameters? How would I be able to reference my jobWeight hashmap from within this comparator class?

class CompareJobs{

map<string, int> jobWeight;


CompareJobs(map<string, int> &jobWeight){
jobWeight = jobWeight;

bool operator () (const Jobs &a, const Jobs &b){

return jobWeight.find(a)->second < jobWeight.find(b)->second;




std::priority_queue's default constructor actually takes optional parameters:

explicit priority_queue(const Compare& x = Compare(), Container&& = Container());

You will note that the first parameter is an instance of the comparator class.

Construct your comparator class first, making it reference your hashmap in whatever way is convenient for you, then use the comparator class to construct your priority queue.