C ++优先级队列中的多重比较?

Multiple comparisons in a c++ priority queue?

我正在尝试模拟 "jobs" 进入打印机。这些作业已根据处理时间添加到优先级队列中。我还想进行另一个比较,其中优先级为 1 的作业的位置高于优先级为 0 的作业,尽管它们有处理时间。

这是我的代码片段

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';

    }
}

考虑以下代码:

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

    bool operator <(const Jobs& other) const {
        const auto neg_lhs = -processingTime;
        const auto neg_rhs = -other.processingTime;
        return std::tie(priority, neg_lhs) < std::tie(other.priority, neg_rhs);
    }

    friend std::ostream& operator <<(std::ostream& out, const Jobs& arg) {
        return out << arg.arrivalTime;
    }
};

int main() {
    std::vector<Jobs> source {
            // consecutive arrival times to distinguish the elements easily
            Jobs {1, 1, 1, 1, 1},
            Jobs {0, 1, 2, 1, 1},
            Jobs {2, 2, 3, 1, 1},
            Jobs {0, 2, 4, 1, 1}
    };

    std::priority_queue<Jobs> jobs(source.begin(), source.end());

    while(!jobs.empty()) {
        std::cout << jobs.top() << ' ';
        jobs.pop();
    }
}

注意 operator< 在实际 class Jobs 中的存在,它将使用依赖于 std::tie 的技巧按字典顺序比较两个 Jobs 对象20=].

我还加了operator<<,方便输出Jobs个对象,所以main()里的测试更方便。这个程序的输出是:

3 1 4 2

让您的比较器将优先级较高的作业排在优先级较低的作业之前:

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