List of disfunctionality iterators
I have a little problem: I am using an iterator to loop through a list, but I cannot access the previous positions using just this.
std::list<int>::iterator i;
for(i=mylist.begin();i!=mylist.end();i++)
{
if(*i<0) fprintf(fout,"%d",*(i-1));//here i want to access the (i-1)th element
}
source to share
Here's one way to do it from C ++ 03:
#include <iostream>
#include <list>
int main()
{
std::list<int> mylist { 11, -22, -33, 44, -55 };
std::list<int>::iterator i, j;
if (!mylist.empty())
{
for (i = mylist.begin(); ++i != mylist.end(); )
if (*i < 0)
printf("%d ",*--(j=i));
printf("\n");
}
}
With C ++ 11, you can replace malarky with j
std::prev(i)
as Columbo suggested ....
Note that I've changed your loop to avoid potentially accessing some imaginary "before" element *begin()
. You can see how it works here .
source to share
There are different categories of iterators (see Types of Iterators: Output vs. Input or Direct or Random Access Iterator ). Your code requires a random access iterator whereas it std::list
provides a bidirectional iterator.
One way to get around this is to store the previous value in a variable and use instead *(i-1)
.
source to share