且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从队列中删除特定值

更新时间:2023-11-25 10:53:16

如果要将特定数量的值出列,可以使用循环:

If you want to dequeue a specific number of values, you can use a loop:
int count_to_dequeue = 3; // choose a number
while (count_to_dequeue > 0) {
    queue.dequeue();
    count_to_dequeue--;
}



如何工作:首先,初始化变量 count_to_dequeue 。在示例中,它是 3 ,以使三个值出列。然后有一个while循环。这意味着当count_to_dequeue大于零时,执行块中的代码。在块中,一个值出列并且count_to_dequeue减少一个。



运行时发生的所有步骤的完整列表:


How this works: first, you initialize a variable count_to_dequeue. In the example, it's 3, to dequeue three values. Then there is a while loop. It means "while count_to_dequeue is greater than zero, execute the code in the block". In the block, a value is dequeued and count_to_dequeue is decreased by one.

Full list of all steps that happen on runtime:



  1. count_to_dequeue设置为3.
  2. (进入循环时)
  3. 值已出列。
  4. count_to_dequeue减少 - >它的值为2.
  5. 一个值出列。
  6. count_to_dequeue减少 - >它的值为1.
  7. 一个值出列。
  8. count_to_dequeue减少 - >它的值为0.
  9. (while循环存在:count_to_dequeue不再大于零)