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 
}

      

+3


source to share


4 answers


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 .

+2


source


You can try std::prev

:



fprintf( fout,"%d",*std::prev(i) )

      

+2


source


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)

.

+1


source


std::list<int>::iterator i;

int temp = mylist.begin(); //temp variable to save the past i

for(i = mylist.begin(); i != mylist.end(); i++)
{
    if(*i<0) fprintf(fout,"%d", temp);//here i want to access the (i-1)th element 
    temp = *i;
}

      

Something like that.

0


source







All Articles