Search code examples
c++liststliteratortraversal

How do you iterate backwards through an STL list?


I'm writing some cross-platform code between Windows and Mac.

If list::end() "returns an iterator that addresses the location succeeding the last element in a list" and can be checked when traversing a list forward, what is the best way to traverse the list backwards?

This code works on the Mac but not on Windows (can't decrement beyond first element):

list<DVFGfxObj*>::iterator iter = m_Objs.end();
for (iter--; iter!=m_Objs.end(); iter--)// By accident discovered that the iterator is circular ?
{}

this works on Windows:

list<DVFGfxObj*>::iterator iter = m_Objs.end();
do{
    iter--;
} while (*iter != *m_Objs.begin());

Is there another way to traverse backward that could be implemented in a for loop?


Solution

  • Use reverse_iterator instead of iterator. Use rbegin() & rend() instead of begin() & end().

    Another possibility, if you like using the BOOST_FOREACH macro is to use the BOOST_REVERSE_FOREACH macro introduced in Boost 1.36.0.