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

前端 未结 2 1935
野性不改
野性不改 2020-12-16 21:01

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

相关标签:
2条回答
  • 2020-12-16 21:19

    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;
        }
    }
    
    0 讨论(0)
  • 2020-12-16 21:23

    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;
       }
    }
    
    0 讨论(0)
提交回复
热议问题