Start New Discussion within our Software Development Community

I tried to make a function , using iterators, to walk a deque backward and my function does not work . I would appreciate if somebody cna help me :

double Dq_Iter_Backward()
{


deque<int>::reverse_iterator InvDeqIter;
DeqIter=intdeq.begin();
InvDeqIter = intdeq.end()-1;
for(InvDeqIter = intdeq.end()-1;InvDeqIter!=intdeq.begin()-1;--DeqIter)
{
cout<<InvDeqIter;
}


elapsed = clock()- start_time;
elapsed_time = elapsed / ((double) CLOCKS_PER_SEC);
return elapsed_time;
}

A couple things:

I think you meant --InvDeqiter instead of --DeqIter

otherwise the for loop will likely be never ending as the stop conditional relates to InvDeqIter not DeqIter.

To read a deque or a double ended list backward using a reverse_iterator you increment the reverse iterator, not decrement it. You could decrement a bidirectional iterator to read backward if you wanted to. I believe an iterator without any prefix, like increment_iterator or reverse_iterator, is a bidirectional iterator. Traditionally I would use rbegin() and rend() when working with reverse_iterators, because of decreased risk of off by one errors. For example, in your code if you change --instead of

intdeq.end()-1;

I would use

intdeq.rbegin();

Last, but not least, if you are trying to see what ints are in intdeq you don't want this:

cout<<InvDeqIter;

which outputs the address in InvDeqIter, you want this:

cout << *InvDeqIter;

which dereferences the iterator to the information held at the address in the iterator.

This article has been dead for over six months. Start a new discussion instead.