Using an STL list with current and next iterators

General algorithm for using a “current” and a “next” iterator on an STL list, which doesn’t provide a convenient next() method (random-access containers such as vector do):

std::list<Foo>::iterator currIter, nextIter;

currIter = list.begin();

while(currIter != list.end()) { currIter->doStuff(); // do something with the curr item

nextIter = ++currIter; //advance the iter and set it to next
if(nextIter != list.end()) // still safe to use next item
{
    nextIter-&gt;doStuff(); // do something with the next item
}

}

Leave a Reply