public member function

std::set::erase

<set>
     void erase ( iterator position );
size_type erase ( const key_type& x );
     void erase ( iterator first, iterator last );
Erase elements
Removes from the set container either a single element or a range of elements ([first,last)).

This effectively reduces the container size by the number of elements removed, calling each element's destructor before.

Parameters

position
Iterator pointing to a single element to be removed from the set.
iterator is a member type, defined as a bidirectional iterator type.
x
Value to be removed from the set.
key_type is a member type defined in set containers as an alias of Key, which is the first template parameter and the type of the elements stored in the container.
first, last
Iterators specifying a range within the set container to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.

Return value

Only for the second version, the function returns the number of elements erased, which in set containers is 1 if an element with a value of x existed (and thus was subsequently erased), and zero otherwise.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// erasing from set
#include <iostream>
#include <set>
using namespace std;

int main ()
{
  set<int> myset;
  set<int>::iterator it;

  // insert some values:
  for (int i=1; i<10; i++) myset.insert(i*10);  // 10 20 30 40 50 60 70 80 90

  it=myset.begin();
  it++;                                         // "it" points now to 20

  myset.erase (it);

  myset.erase (40);

  it=myset.find (60);
  myset.erase ( it, myset.end() );

  cout << "myset contains:";
  for (it=myset.begin(); it!=myset.end(); ++it)
    cout << " " << *it;
  cout << endl;

  return 0;
}

Output:
myset contains: 10 30 50

Complexity

For the first version ( erase(position) ), amortized constant.
For the second version ( erase(x) ), logarithmic in container size.
For the last version ( erase(first,last) ), logarithmic in container size plus linear in the distance between first and last.

See also