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
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With