How to call erase with a reverse iterator



I am trying to do something like this:

for ( std::list< Cursor::Enum >::reverse_iterator i = m_CursorStack.rbegin(); i != m_CursorStack.rend(); ++i )
    if ( *i == pCursor )
        m_CursorStack.erase( i );

However erase takes an iterator and not a reverse iterator. is there a way to convert a reverse iterator to a regular iterator or another way to remove this element from the list?

12/2/2009 1:41:09 AM

Accepted Answer

After some more research and testing I found the solution. Apparently according to the standard [24.4.1/1] the relationship between i.base() and i is:

&*(reverse_iterator(i)) == &*(i - 1)

(from a Dr. Dobbs article):

alt text

So you need to apply an offset when getting the base(). Therefore the solution is:

m_CursorStack.erase( --(i.base()) );


Updating for C++11.

reverse_iterator i is unchanged:

m_CursorStack.erase( std::next(i).base() );

reverse_iterator i is advanced:

std::advance(i, 1);
m_CursorStack.erase( i.base() );

I find this much clearer than my previous solution. Use whichever you require.

2/8/2017 2:17:49 PM

Please note that m_CursorStack.erase( (++i).base()) may be a problem if used in a for loop (see original question) because it changes the value of i. Correct expression is m_CursorStack.erase((i+1).base())

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow