简体   繁体   中英

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... . Why so?

You never update the integer 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.

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 . You initialized it as int val = q.front() and that was the last time it got changed.

Either modify val , eg q.push_back(++val); or print the contents of 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.

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. 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

for ( ; !q.empty(); q.pop_front() ) 
{
    std::cout << q.front() << '\n';
    q.push_back( q.front() + 1 );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM