Data Structures · Priority Queues · std::priority_queue

Hero Task Manager

Tasks keep appearing for the hero: fight a monster, defend the village, heal a wound, repair gear, collect resources. A plain queue does them in the order they arrive. A priority queue always hands back the most important one first. Pick a comparator, then watch the C++ game loop run one second at a time.

A monster attacks

Three "collect resources" tasks (2 seconds each) are waiting when a monster appears. Who does the hero face next?

The comparator decides

std::priority_queue keeps the "largest" element on top, and the comparator says what largest means. It returns true when t1 should come after t2. Choose a rule, or write your own; the game below uses the same rule.


        
        
Ask it: comp(,)

Push these six, then pop until empty

The hero does them in this order

Watch the hero work

Each step is one second of heroTaskManagerSimulation. A new task appears with probability 3/4 until all of them have appeared. The hero finishes one task before taking the next from the top of the queue. The output matches the real program for the same seed.

Compiled with
Time –

New task

Working on

Waiting (next first)

Timeline

waiting in the queuehero working on it (color = priority)

Average wait before the hero started a task

Wait = the second the hero started the task minus the second it appeared. This is the summary the program prints at the end.

Program output

Which rule is best?

The same tasks (same seed and settings as above) run under each rule. Try it in C++ first; then open this to check your table.

Compare the rules

Shortest job first gives the lowest average, because fewer tasks sit behind long ones. Priority order keeps urgent waits low instead, and the lowest priorities pay for it: that is starvation.