Reputation: 7766
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
Upvotes: 0
Views: 102
Reputation: 35
If you print i inside the while loop it produce always 11 because above your code. You already use int i in the for loop, with the last value is 10. Debug your code with ddebugging tools ini your editor again, you will know what you'r doing wrong.
while (d2 != deq.end() )
{
cout<<i<<endl;
d2++;
}
The above while always produce 11 every iteration.
Upvotes: 0
Reputation: 10333
int main()
{
deque <int> deq;
int i;
for ( i= 1 ;i <=10 ;i++)
{
deq.push_front(i);
}
===> i
is 11 here (i <= 10)
is false at 11
deque <int>::iterator d2;
d2 = deq.begin();
===> here you really want to use d2
while (d2 != deq.end() )
{
cout<<i
===> here you print i
instead of d2
<<endl;
d2++;
}
}
Upvotes: 1
Reputation: 19032
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.
Upvotes: 2
Reputation: 726479
You should replace this
cout << i << endl;
with something that actually remove things from the dequeue:
cout << deq.pop_front() << endl;
To avoid simple errors like this in the future, restrict the scope of loop index variables by declaring them inside the loop header:
for (int i= 1 ;i <=10 ;i++)
{
deq.push_front(i);
}
This way you would get a compile error trying to reference i
outside the loop.
Upvotes: 1
Reputation: 17486
You're printing i
, which was assigned to i=11
in the for
loop.
Upvotes: 1