如何使用 std::reverse_iterator 擦除 *AND CONTINUE*?

2022-01-10 00:00:00 iterator c++ stl erase

我一直在使用 stackoverflow,甚至是非常非常好的 Dr.Dobbs 的文章,但我找不到这个问题的明确答案.

I've been up and down stackoverflow and even the very, very nice Dr. Dobbs article but I can't find a definitive answer to the question.

部分问题的答案std有什么缺点::reverse_iterator? 说这可能根本不可能.

A section of the answer to the question What are the shortcomings of std::reverse_iterator? says that it might not be possible at all.


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(),但我正在寻找这个特定问题的答案.

PS: I do know there are other alternatives, such as erase_if(), but I'm looking for an answer to this specific question.

推荐答案

应该就是

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;
   }
}

相关文章