Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List iterator disfunctionality

Tags:

c++

list

I have a small problem: I am using an iterator to go through a list, but I can't seem to access previous positions using just it.

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 
}
like image 584
Mihnea Gafton Avatar asked Apr 01 '26 00:04

Mihnea Gafton


1 Answers

Here's one way to do it that works with 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 the malarky with j with std::prev(i), as Columbo first suggested....

Notice that I changed your loop to avoid potential attempted access to some imagined element "before" *begin(). You can see it running here.

like image 65
Tony Delroy Avatar answered Apr 03 '26 12:04

Tony Delroy