Reference
C Library
IOstream Library
Strings library
STL Containers
STL Algorithms
Miscellaneous
STL Containers
bitset
deque
list
map
multimap
multiset
priority_queue
queue
set
stack
vector
map
comparison operators
map::map
map::~map
member functions:
map::begin
map::clear
map::count
map::empty
map::end
map::equal_range
map::erase
map::find
map::get_allocator
map::insert
map::key_comp
map::lower_bound
map::max_size
map::operator=
map::operator[]
map::rbegin
map::rend
map::size
map::swap
map::upper_bound
map::value_comp


map::erase

public member function
     void erase ( iterator position );
size_type erase ( const key_type& x );
     void erase ( iterator first, iterator last );

Erase elements

Removes from the map 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.

Parameters

position
Iterator pointing to a single element to be removed from the map.
iterator is a member type, defined as a bidirectional iterator type.
x
Value to be removed from the map.
key_type is a member type defined in map containers as an alias of Key, which is the first template parameter and the type of the elements' keys.
first, last
Iterators specifying a range within the map 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 map containers is 1 if an element with a key 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
31
32
// erasing from map
#include <iostream>
#include <map>
using namespace std;
int main ()
{
  map<char,int> mymap;
  map<char,int>::iterator it;
  // insert some values:
  mymap['a']=10;
  mymap['b']=20;
  mymap['c']=30;
  mymap['d']=40;
  mymap['e']=50;
  mymap['f']=60;
  it=mymap.find('b');
  mymap.erase (it);                   // erasing by iterator
  mymap.erase ('c');                  // erasing by key
  it=mymap.find ('e');
  mymap.erase ( it, mymap.end() );    // erasing by range
  // show content:
  for ( it=mymap.begin() ; it != mymap.end(); it++ )
    cout << (*it).first << " => " << (*it).second << endl;
  return 0;
}

Output:
a => 10
d => 40

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