I'm trying to extend PHP's SplMinHeap so I can limit the amount of items my heap can hold. The problem is, when I try to access the top element, which should be the min, it gives me the max value. The code I have so far is pretty simple:
class MyHeap extends SplMinHeap {
public static $limit = 10;
public function compare($value1, $value2) {
return ($value1 - $value2);
}
public function myInsert($value) {
if ( $this->count() < self::$limit ) {
$this->insert($value);
} else {
var_dump($this->top());
}
}
};
When I insert the numbers 1 to 15 I would expect it to print 1 5 times, instead it prints 10. I also tried extending the insert method, using the same code as myInsert
but replacing $this->insert
with parent::insert
. I just didn't know whether that would use my extended compare
or the default one, that's why I switched it.
Strangely enough, if use a normal SplMinHeap and insert the same numbers I will get 1 when calling top()
.
Can anyone help me figure out what I'm doing wrong?