SplPriorityQueue :: next () removes an element
I would like to know how I could repeat SplHeap or SplPriorityQueue multiple times.
The next () method removes the last element, so the second foreach (or for) gets no result.
Example:
<?php
class Teste extends SplPriorityQueue {}
$teste = new Teste();
$teste->insert( 'A', 1 );
$teste->insert( 'B', 3 );
$teste->insert( 'D', 5 );
$teste->insert( 'C', 2 );
$teste->insert( 'A', 4 );
echo '<pre>';
var_dump( $teste->count() );
echo '<br>';
foreach( $teste as $t )
var_dump( $t );
echo '<br>';
var_dump( $teste->count() );
Return:
int(5)
string(1) "D"
string(1) "A"
string(1) "B"
string(1) "C"
string(1) "A"
int(0) <--- I need this to still be 5
I need to insert elements based on compare () method, for example: http://php.net/manual/en/splheap.compare.php
Thank!
+3
source to share
1 answer
I would like to know how I could repeat SplHeap or SplPriorityQueue multiple times.
Short answer: you are not repeating multiple times for a single instance of a class.
A somewhat longer answer is to use multiple identical instances instead of multiple repetitions. This can easily be achieved by iterating over the clone
heap / pqueue.
Quick example
<?php
$queue = new SplPriorityQueue();
$queue ->insert('A', 30);
$queue ->insert('C', 10);
$queue ->insert('B', 20);
var_dump(count($queue));
foreach (clone $queue as $item) {
var_dump($item);
}
var_dump(count($queue));
foreach (clone $queue as $item) {
var_dump($item);
}
var_dump(count($queue));
The above outputs:
int(3)
string(1) "A"
string(1) "B"
string(1) "C"
int(3)
string(1) "A"
string(1) "B"
string(1) "C"
int(3)
+4
source to share