简体   繁体   中英

How do you erase *AND CONTINUE* using a std::reverse_iterator?

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.

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: I do know there are other alternatives, such as erase_if(), but I'm looking for an answer to this specific question.

It should just be

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

Most erase() implementations I have seen return the next iterator in the sequence for exactly this kind of situation, eg:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM