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;
}
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!