Search code examples
c++debuggingstldeque

simple deque programme exhibit weird behaviour


I am using a deque to store integers from 1 to 10 and output to console 1 to 10 but for some unknown reason it outputs 11 for every loop . I cannot figure out what i am doing wrong.

#include <iostream>
#include <cstring>
#include <deque>
using namespace std;




int main()
{
    deque <int> deq;

    int i;

    for ( i= 1 ;i <=10 ;i++)
    {
       deq.push_front(i);
    }

    deque <int>::iterator d2;

    d2 = deq.begin();

    while (d2 != deq.end() )
    {
        cout<<i
            <<endl;

            d2++;
    }


}

Thanks for the help , i understand the problem already


Solution

  • You need to print out the value contained by the iterator, not i:

    while (d2 != deq.end() )
    {
        // wrong!
        //cout<<i
        //    <<endl;
    
        cout << *d2 << endl;
    
            d2++;
    }
    

    As a side note, this illustrates why you should always limit the scope of variables to the smallest possible scope. Had your original loop been declared as:

    for(int i = 1; i <= 10; ++i)
    

    Then attempting to print out i (incorrectly) later would have been a compile time error.