我一直在上下堆栈流,甚至非常非常好Dr. Dobbs article但是我找不到这个问题的明确答案。
问题What are the shortcomings of std::reverse_iterator?的答案部分说明可能根本不可能。
std::list::reverse_iterator it = list.rbegin();
while( it != list.rend() )
{
int value=*it;
if( some_cond_met_on(value) )
{
++it;
list.erase( it.base() );
}
else
{
++it;
}
}
PS:我知道还有其他选择,例如erase_if(),但我正在寻找这个特定问题的答案。
答案 0 :(得分:15)
应该只是
std::list<int>::reverse_iterator it = list.rbegin();
while( it != list.rend() )
{
int value=*it;
if( some_cond_met_on(value) )
{
++it;
it= reverse_iterator(list.erase(it.base()); // change to this!
}
else
{
++it;
}
}
答案 1 :(得分:0)
我见过的大多数erase()
实现都会返回序列中的下一个迭代器,以满足这种情况,例如:
std::list<int>::reverse_iterator it = list.rbegin();
while( it != list.rend() )
{
int value = *it;
if( some_cond_met_on(value) )
{
it = list.erase( it );
}
else
{
++it;
}
}