论如在C++中何用正确的姿势边迭代、边删除reverse_iterator

在C++的容器中,我们可以边迭代边删除,如下:

std::list<int>::iterator itr = list.begin(); 
while(itr != list.end();) { 
    if(condition) 
        itr = list.erase(itr); 
    else ++itr; 
}

但是,有时候,我们希望使用reverse_iterator也做这个工作:边迭代、边删除:

这个有有点麻烦了,首先要都用rbegin、rend。。其次,erase的时候有点trick,如下:

std::list<int>::reverse_iterator ritr = list.rbegin();
while(ritr != list.rend();)
{
    if(condition)
        ritr = std::list<int>::reverse_iterator(list.erase(--(ritr.base())));
    else
        ritr++;
}

或者:

std::list<int>::reverse_iterator ritr = list.rbegin();
while(ritr != list.rend();)
{
    if(condition)
        ritr = std::list<int>::reverse_iterator(list.erase((++ritr).base())));
    else
        ritr++;
}

看着很不科学是吧?--和++居然都行?想知道为什么的,请看参考文献。。

参考文献:http://stackoverflow.com/questions/1830158/how-to-call-erase-with-a-reverse-iterator

Leave a Reply

Your email address will not be published. Required fields are marked *