erase
Syntax:
#include <list> iterator erase( iterator loc ); iterator erase( iterator start, iterator end );
The erase() function either deletes the element at location loc, or deletes the elements between start and end (including start but not including end). The return value is the element after the last element erased.
The first version of erase (the version that deletes a single element at location loc) runs in constant time for lists and linear time for vectors, deques, and strings. The multiple-element version of erase always takes linear time.
Lists have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed.
The ordering of iterators may be changed (that is, list<T>::iterator might have a different predecessor or successor after a list operation than it did before), but the iterators themselves will not be invalidated or made to point to different elements unless that invalidation or mutation is explicit.
For example:
// Create a list, load it with the first ten characters of the alphabet list<char> alphaList; for( int i=0; i < 10; i++ ) { alphaList.push_back( i + 65 ); } int size = alphaList.size(); list<char>::iterator startIterator; list<char>::iterator tempIterator; for( int i=0; i < size; i++ ) { startIterator = alphaList.begin(); alphaList.erase( startIterator ); // Display the list copy( alphaList.begin(), alphaList.end(), ostream_iterator<char>(cout) ); cout << endl; }
That code would display the following output:
BCDEFGHIJ CDEFGHIJ DEFGHIJ EFGHIJ FGHIJ GHIJ HIJ IJ J
In the next example, erase() is called with two iterators to delete a range of elements from a list:
// create a list, load it with the first ten characters of the alphabet list<char> alphaList; for( int i=0; i < 10; i++ ) { alphaList.push_back( i + 65 ); } // display the complete list copy( alphaList.begin(), alphaList.end(), ostream_iterator<char>(cout) ); cout << endl; // use erase to remove all but the first two and last three elements // of the list alphaList.erase( advance(alphaList.begin(),2), advance(alphaList.end(),-3) ); // display the modified list copy( alphaList.begin(), alphaList.end(), ostream_iterator<char>(cout) ); cout << endl;
When run, the above code displays:
ABCDEFGHIJ ABHIJ
Related Topics: clear, insert, pop_back, pop_front, remove, remove_if