Skip to content

Core\Heap::count

$heap->count(): uint

Returns how many values a heap has.

Every push adds one to the count and every pop removes one. A value that was added twice is counted twice. A new heap has a count of 0. The count is a uint, a whole number that is never negative.

Good to know: to check whether a heap is empty, isEmpty says it more clearly than comparing the count with 0.

Return value

Returns uint. The number of elements. An empty heap gives 0.

Examples

Count after each push

<?nvs
// Shows how the count of a heap grows with each value you add.
var $heap = new Core\Heap<int>();
// A new heap has no values. This prints 0.
echo $heap->count(), "\n";
$heap->push(10);
$heap->push(30);
$heap->push(20);
// This prints 3.
echo $heap->count(), "\n";
Output
0
3

Duplicates and pops

<?nvs
// Shows that the count includes every copy of a value, and goes down with each `pop`.
var $heap = new Core\Heap<string>();
$heap->push('red');
$heap->push('red');
$heap->push('blue');
// "red" was added twice, so this prints 3.
echo $heap->count(), "\n";
// `pop` takes out "blue", the first value in alphabetical order. This prints 2.
$heap->pop();
echo $heap->count(), "\n";
Output
3
2

Jobs waiting

<?nvs
// Shows a worker that reports how many jobs are still waiting after each job it finishes.
var $jobs = new Core\Heap<int>();
$jobs->push(3);
$jobs->push(1);
$jobs->push(2);
// Each job here is a number, and the lowest number runs first.
while (!$jobs->isEmpty()) {
int $job = $jobs->pop();
echo 'finished job ', $job, ', ', $jobs->count(), " waiting\n";
}
Output
finished job 1, 2 waiting
finished job 2, 1 waiting
finished job 3, 0 waiting