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++ )
      alphas.insert( alphas.end(), i + 65 );
 
    // 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')
        // A copy of iter is passed into erase(), ++ is executed after erase().
        // Thus iter 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