如何使用反向迭代器调用erase [英] How to call erase with a reverse iterator
问题描述
我想这样做:
for ( std::list< Cursor::Enum >::reverse_iterator i = m_CursorStack.rbegin(); i != m_CursorStack.rend(); ++i )
{
if ( *i == pCursor )
{
m_CursorStack.erase( i );
break;
}
}
但是,擦除需要一个迭代器而不是一个反向迭代器。是否有一种方法可以将反向迭代器转换为常规的迭代器,或者从列表中删除此元素的另一种方式?
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?
推荐答案
一些更多的研究和测试我发现了解决方案。显然根据标准[24.4.1 / 1],i.base()和i之间的关系是:
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)
< a href =http://www.ddj.com/cpp/184401406> Dr。Dobbs文章):
因此,您需要应用偏移当获取base()时。因此解决方案是:
So you need to apply an offset when getting the base(). Therefore the solution is:
m_CursorStack.erase( --(i.base()) );
EDIT
更新C ++ 11。
reverse_iterator i
未更改:
reverse_iterator i
is unchanged:
m_CursorStack.erase( std::next(i).base() );
reverse_iterator i
是高级:
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.
这篇关于如何使用反向迭代器调用erase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!