Search code examples
c++loopsfor-loopinfinite-loopdeque

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?


Solution

  • 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 e.g. by

    for (int val = q.front(); !q.empty(); q.pop_front(), val = q.front())
    {
       // as before...
    }