gpt4 book ai didi

php - 使用 SplQueue 无限循环

转载 作者:搜寻专家 更新时间:2023-10-31 21:08:18 27 4
gpt4 key购买 nike

我需要一个队列,我可以在队列中添加对象(先进先出)。此外,我会跟踪 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,使用 dequeueresult 代替:

$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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com