- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
我需要一个队列,我可以在队列中添加对象(先进先出)。此外,我会跟踪 HashMap 中没有重复的对象。
<?php
$test = new \SplQueue();
$done = array();
// Put 'test a' in queue
$test->enqueue('test a');
// While we have objects in the queue...
while ($test->valid()) {
// Echo the current object
$current = $test->current();
echo $current, PHP_EOL;
// Remove the current object and add it to "done"
$test->dequeue();
$done[$current] = 1;
// Add more to queue
$new = array('test a', 'test b', 'test c');
foreach ($new as $newObject) {
if (! isset($done[$newObject])) {
$test->enqueue($newObject);
}
}
}
在 PHP codepad 中,我没有得到任何结果。怎么了?
更新:一段时间后我得到输出:
test a
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /code/NIPg42 on line 25
PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in /code/NIPg42 on line 25
我对已经完成的对象进行出队和测试,为什么这是一个无限循环?
第 25 行是 $test->enqueue($newObject);
最佳答案
对我来说,使用 SplQueue 更容易(也更自然),仅使用两种基本方法:enqueue
将一个项目放在队列的末尾queue 和 dequeue
从队列的开头提取您必须处理的项目。这意味着摆脱 current
,使用 dequeue
的 result 代替:
$current = $test->dequeue();
$done[$current] = 1;
var_dump($current); // or any other processing
由于尝试使空列表出列会导致错误,因此您必须先检查它。所以你的代码变得类似于这样:
$test = new \SplQueue();
$done = array();
// Put 'test a' in queue
$test->enqueue('test a');
// While we have objects in the queue...
while (!$test->isEmpty()) {
$item = $test->dequeue();
$done[$item] = 1;
var_dump($item);
// Add more to queue
$new = array('test a', 'test b', 'test c');
foreach ($new as $newObject) {
if (! isset($done[$newObject])) {
$test->enqueue($newObject);
// without this line, `test c` will be enqueued twice.
$done[$newObject] = 1;
}
}
}
Demo .如您所见,这里还有另一个变化:在执行 enqueue
之前设置哈希。如果您确实想创建一个 HashQueue(某种),我建议您创建自己的类(扩展或使用 SplQueue); key 将伴随每个 enqueue
操作以及相应的哈希检查/添加。
关于php - 使用 SplQueue 无限循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28263302/
我需要一个队列,我可以在队列中添加对象(先进先出)。此外,我会跟踪 HashMap 中没有重复的对象。 enqueue('test a'); // While we have objects in t
队列这种数据结构更简单,就像我们生活中排队一样,它的特性是先进先出(FIFO)。 PHP SPL中SplQueue类就是实现队列操作,和栈一样,它也可以继承双链表(SplDoublyLinke
我是一名优秀的程序员,十分优秀!