Search code examples
c++queuepriority-queue

Multiple comparisons in a c++ priority queue?


I am trying to simulate "jobs" coming into a printer. The jobs have been added to a priority queue based on processing time. I would also like to have another comparison where jobs with a priority of 1 are placed higher than jobs with a priority of 0 despite their processing time.

Here's a snippet of my code

struct Jobs{
    int priority; 
    int processingStatus;
    int arrivalTime; 
    int processingTime; 
    char jobType; 
};

struct Comp {
    bool operator()(const Jobs& a, const Jobs& b) {
        return a.processingTime > b.processingTime;
    }
};
void createJobs(Jobs jobsA[], Jobs jobsB[], Jobs jobsC[], Jobs jobsD[]) {
    for (int i = 0; i < 100; i++) {
        jobsA[i].arrivalTime = 4 + rand() % 3 + i; 
        jobsA[i].processingTime = 1 + rand() % 4; 
        jobsA[i].priority = 0; 
        jobsA[i].jobType = 'A'; 

        jobsD[i].arrivalTime = 25 + rand() % 10 + i ; 
        jobsD[i].processingTime = 8 + rand() % 4;
        jobsD[i].priority = 1; 
        jobsD[i].jobType = 'D';

    }
}

Solution

  • Make your comparator order higher priority jobs before those with lower priority:

    bool operator()(const Jobs& a, const Jobs& b) {
        if (a.priority == b.priority {
             return a.processingTime > b.processingTime;
        } else {
             return a.priority > b.priority;
        }
     }