Baza znanjaIzpitno središče
SLSlovenščina
Izberi jezik13

CKTIS / PHP

SplHeap

Razširite abstraktno kopico in določite prednost s compare.

Različica: PHP 8.4; repository runtime, production runtime not attested

Sintaksa

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

Razširite abstraktno kopico in določite prednost s compare. Pozitiven rezultat da prednost prvemu argumentu. top prebere najvišji element, extract ga odstrani. Pri izenačenju brez dodatnega merila vrstni red ni zagotovljen.

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"]

Primeri

<?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()]);

Rezultat

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

Viri