erase

C++ Reference

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, dequeues, and strings. The multiple-element version of erase always takes linear time.

For example:

 // Create a vector, load it with the first ten characters of the alphabet
 vector<char> alphaVector;
 for( int i=0; i < 10; i++ ) {
   alphaVector.push_back( i + 65 );
 }
 int size = alphaVector.size();
 vector<char>::iterator startIterator;
 vector<char>::iterator tempIterator;
 for( int i=0; i < size; i++ ) {
   startIterator = alphaVector.begin();
   alphaVector.erase( startIterator );
   // Display the vector
   for( tempIterator = alphaVector.begin(); tempIterator != alphaVector.end(); tempIterator++ ) {
     cout << *tempIterator;
   }
   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 vector:

 // create a vector, load it with the first ten characters of the alphabet
 vector<char> alphaVector;
 for( int i=0; i < 10; i++ ) {
   alphaVector.push_back( i + 65 );
 }
 // display the complete vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;            

 // use erase to remove all but the first two and last three elements
 // of the vector
 alphaVector.erase( alphaVector.begin()+2, alphaVector.end()-3 );
 // display the modified vector
 for( int i = 0; i < alphaVector.size(); i++ ) {
   cout << alphaVector[i];
 }
 cout << endl;            

When run, the above code displays:

 ABCDEFGHIJ
 ABHIJ          
Related topics: