2011年1月26日 星期三

How to delete items from the end of a list

We can erase vector and list from any iterator of itself, but if we want to erase a number of items from the end, HOW??

The "erase" can not accept the reverse_iterator type. It only accepts the iterator. So, we have to use the reverse_iterator.base() to get current iterator. You can trace into the source code to get the point of the implementation of STL about the reverse_iterator. When you "++" a reverse_iterator, it will return --current. Got it!? The reverse iterator uses the order by reversing!

Following is the sample code to erase the list from the end.

How about the vector? If you change the list to vector, this code will fail. Think about it. vector can get the size. If you want to erase a number of items (n Items), just erase(vector.begin() + n, vector.end()); That all of it. List can not use this method. Why not? Try to use list.begin() + n, you will get some errors.

 

#include <list>

using namespace std;

int main(int argc, char* argv[])

{

    list<int> listInt;

    listInt.push_back(1);

    listInt.push_back(2);

    listInt.push_back(3);

    listInt.push_back(4);

    listInt.push_back(5);

    listInt.push_back(6);

    list<int>::reverse_iterator rIt = listInt.rbegin();

    for(; rIt != listInt.rend(); ++rIt) {

        listInt.erase(--rIt.base());

    }

    return 0;

}