[英]Infinite loop with a 'deque' in c++
I have a problem with the following code: 我的以下代码有问题:
#include <iostream>
#include <deque>
using namespace std;
int main() {
deque<int> q = {1};
for (int val = q.front(); !q.empty(); q.pop_front()) {
cout << val << endl;
q.push_back(val + 1);
q.push_back(val + 2);
}
}
It produces an infinite loop (which is correct) but instead of printing 1 2 3 4 ...
it prints a 1 1 1 1 1...
. 它产生一个无限循环(正确),但不是打印
1 2 3 4 ...
而是打印1 1 1 1 1...
Why so? 为什么这样?
You never update the integer val
. 您永远不会更新整数
val
。 It is only initialized in the first part of your for loop, and as you copied the first value of the container into it, this one keeps being printed. 它仅在for循环的第一部分中初始化,并且在您将容器的第一个值复制到其中时,该值一直被打印。
You can fix that eg by 您可以通过例如解决此问题
for (int val = q.front(); !q.empty(); q.pop_front(), val = q.front())
{
// as before...
}
That's because you never modify the value of val
. 这是因为您永远不会修改
val
的值。 You initialized it as int val = q.front()
and that was the last time it got changed. 您将其初始化为
int val = q.front()
,这是最后一次更改它。
Either modify val
, eg q.push_back(++val);
要么修改
val
,例如q.push_back(++val);
or print the contents of deque<int> q
. 或打印
deque<int> q
的内容。
There are two problems with the loop. 循环有两个问题。
The first one is that the variable val is not changed in the loop and its initial value that is set in the init part of the loop is always outputted. 第一个是变量val在循环中不更改,并且始终输出在循环的init部分中设置的初始值。
for (int val = q.front(); !q.empty(); q.pop_front()) {
^^^^^^^^^^^^^^^^^^^
cout << val << endl;
q.push_back(val + 1);
q.push_back(val + 2);
}
The second one is that you are pushing two
values on the dequeue and after that it contains three
values including the previous one. 第二个是您要在出队时推送
two
值,之后它包含three
值,包括前一个。 But in the third part of the loop the expression 但是在循环的第三部分,表达式
q.pop_front()
pops only one value from the dequeue. 从出队中仅弹出一个值。
The loop can look the following way 循环如下所示
#include <iostream>
#include <deque>
int main()
{
std::deque<int> q = { 1 };
for ( ; !q.empty(); q.pop_front() )
{
auto val = q.front();
std::cout << val << '\n';
q.push_back( ++val );
}
}
Or the loop can be written without using an intermediate variable var
like 或者可以不使用中间变量
var
来编写循环
for ( ; !q.empty(); q.pop_front() )
{
std::cout << q.front() << '\n';
q.push_back( q.front() + 1 );
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.