KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / PHP

SplHeap

Breid de abstracte heap uit en definieer met compare de prioriteit.

Versie: PHP 8.4; repository runtime, production runtime not attested

Syntax

class ByLength extends SplHeap { protected function compare(mixed $a, mixed $b): int { return strlen($a) <=> strlen($b); } }

Breid de abstracte heap uit en definieer met compare de prioriteit. Een positieve uitkomst geeft het eerste argument voorrang. top leest het hoogste element, extract verwijdert het. Bij gelijkstand is zonder extra criterium geen volgorde beloofd.

class ByLength extends SplHeap { protected function compare(mixed $a,mixed $b): int{return strlen($a)<=>strlen($b);} }
$heap=new ByLength(); foreach(["aa","xxxx","b"] as $s){$heap->insert($s);}
echo json_encode([$heap->top(),$heap->count(),$heap->extract(),$heap->top()]);
["xxxx",3,"xxxx","aa"]

Voorbeelden

<?php
class ByLength extends SplHeap { protected function compare(mixed $a,mixed $b): int{return strlen($a)<=>strlen($b);} }
$heap=new ByLength(); foreach(["aa","xxxx","b"] as $s){$heap->insert($s);}
echo json_encode([$heap->top(),$heap->count(),$heap->extract(),$heap->top()]);

Resultaat

["xxxx",3,"xxxx","aa"]

Bronnen