Skip to content

Core\Heap::pop

$heap->pop(): T

Removes the smallest value from a heap and returns it.

After pop, the next smallest value moves to the front, so calling pop again and again gives every value in order. This stays fast even when the heap has many values. By default the smallest value comes first. To get the largest value first, give new Core\Heap a comparator function that compares the other way round.

In plain words: a heap is like a waiting room where the most urgent patient is always called next, whatever order the patients arrived in.

Good to know: pop on an empty heap throws a RuntimeError. Call isEmpty first when the heap can be empty.

Return value

Returns T. The element that was first. The next element becomes first. If the comparator throws an error, pop throws the same error.

Errors

  • RuntimeErrorThe heap is empty. It also throws when sorting the other elements meets two values with no natural order, or a comparator that returns NaN.

Examples

Take the smallest

<?nvs
// Shows how `pop` takes the smallest value out of a heap.
var $heap = new Core\Heap<int>();
$heap->push(4);
$heap->push(1);
$heap->push(3);
// This prints 1.
echo $heap->pop(), "\n";
// The 1 is gone, so this prints 2.
echo $heap->count(), "\n";
// The next smallest value is now at the front. This prints 3.
echo $heap->pop(), "\n";
Output
1
2
3

Largest first

<?nvs
// Shows how to make `pop` return the largest value first.
// The comparator returns `$b - $a`, which is the opposite of the normal order.
var $heap = new Core\Heap<int>(fn(int $a, int $b): int => $b - $a);
$heap->push(20);
$heap->push(50);
$heap->push(10);
// This prints 50, 20 and 10.
while (!$heap->isEmpty()) {
echo $heap->pop(), "\n";
}
Output
50
20
10

The three cheapest offers

<?nvs
// Shows how to find the three cheapest offers in a list of shipping offers.
class Offer
{
public string $carrier;
public int $cents;
public function constructor(string $carrier, int $cents)
{
$this->carrier = $carrier;
$this->cents = $cents;
}
}
// The comparator puts the lower price first.
var $offers = new Core\Heap<Offer>(fn(Offer $a, Offer $b): int => $a->cents - $b->cents);
$offers->push(new Offer('Express', 1490));
$offers->push(new Offer('Standard', 590));
$offers->push(new Offer('Economy', 390));
$offers->push(new Offer('Same day', 2990));
$offers->push(new Offer('Pickup point', 450));
// Each `pop` takes the cheapest offer that is left. This prints Economy, Pickup point and Standard.
int $shown = 0;
while ($shown < 3) {
var $offer = $offers->pop();
echo $offer->carrier, ': ', $offer->cents, " cents\n";
$shown = $shown + 1;
}
Output
Economy: 390 cents
Pickup point: 450 cents
Standard: 590 cents