erase

Syntax:

    #include <set>
    void erase( iterator pos );
    void erase( iterator start, iterator end );
    size_type erase( const key_type& key ); // returns number of erased elements

The erase function() either erases the element at pos, erases the elements between start and end, or erases all elements that have the value of key.

With all container types you have to be careful when inserting or erasing elements, since it may lead to invalid iterators.

Especially, set::erase() only invalidates the iterators (and pointers) referencing the element to be erased.

The example erases some elements depending on a condition (it will erase the letters B and D):

#include <iostream>
#include <set>
#include <iterator>
 
using namespace std;
 
int main()
{
    // Create a set, load it with the first ten characters of the alphabet
    set<char> alphas;
    for( int i=0; i < 10; i++ )
    {
      static const char letters[] = "ABCDEFGHIJ";
      alphas.insert( alphas.end(), letters[i] );
    }
 
    // display content before
    copy(alphas.begin(), alphas.end(), ostream_iterator<char>(cout, ""));
    cout << endl;
 
    set<char>::iterator iter = alphas.begin();
    while( iter != alphas.end() )
    {
      if (*iter == 'B' || *iter == 'D')
        // Since post-increment is used, erase() gets a temporary object and
        // iter has moved beyond the item being erased so it remains valid.
        alphas.erase( iter++ );
      else
        ++iter;
    }
 
    // display content after
    copy(alphas.begin(), alphas.end(), ostream_iterator<char>(cout, ""));
    cout << endl;
}

When run, the above code displays:

ABCDEFGHIJ
ACEFGHIJ

Related Topics: clear