stl:deque:erase

C++ Reference

erase

Syntax:

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

For example:

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

   // create a deque, load it with the first ten characters of the alphabet
   deque<char> alphaDeque;
   for( int i=0; i < 10; i++ ) {
     alphaDeque.push_back( i + 65 );
   }
   // display the complete deque
   for( int i = 0; i < alphaDeque.size(); i++ ) {
     cout << alphaDeque[i];
   }
   cout << endl;
 
   // use erase to remove all but the first two and last three elements
   // of the deque
   alphaDeque.erase( alphaDeque.begin()+2, alphaDeque.end()-3 );
   // display the modified deque
   for( int i = 0; i < alphaDeque.size(); i++ ) {
     cout << alphaDeque[i];
   }
   cout << endl;

When run, the above code displays:

   ABCDEFGHIJ
   ABHIJ

Related Topics: clear, insert, pop_back, pop_front