LearnFrenzy
Sign in Take a free test

STL Containers · STL Container Programs · Question 6

Job scheduler with priorities and arrival order in C++ Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 6 Back to Exercise

Jobs arrive with a priority; run them highest priority first, and in arrival order for equal priorities, using a priority_queue of structs with a custom comparator.

Solution
main.cpp
#include <iostream>
#include <queue>
#include <string>
#include <vector>

struct Job {
    std::string name;
    int priority;
    int arrival;
};

struct ByPriority {
    bool operator()(const Job& a, const Job& b) const {
        if (a.priority != b.priority) return a.priority < b.priority;   // higher priority first
        return a.arrival > b.arrival;                                    // earlier arrival first
    }
};

int main() {
    std::priority_queue<Job, std::vector<Job>, ByPriority> pq;
    int t = 0;
    for (auto [name, p] : std::vector<std::pair<std::string, int>>{{"backup", 1}, {"email", 3}, {"deploy", 5}, {"report", 3}, {"logs", 1}, {"alert", 5}})
        pq.push({name, p, t++});
    while (!pq.empty()) {
        const Job& j = pq.top();
        std::cout << j.name << '(' << j.priority << ") ";
        pq.pop();
    }
    std::cout << '\n';
    return 0;
}

Output Verified by compiling and running

deploy(5) alert(5) email(3) report(3) backup(1) logs(1)

The comparator returns true when a should come out after b. The arrival number breaks ties, because a heap is not stable on its own.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links