erase

C/C++ Reference

erase
Syntax:
  #include <map>
  void erase( iterator pos );
  void erase( iterator start, iterator end );
  size_type erase( const key_type& key );

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.

For example, the following code uses erase() in a while loop to incrementally clear a map and display its contents in order:

  struct strCmp {
    bool operator()( const char* s1, const char* s2 ) const {
      return strcmp( s1, s2 ) < 0;
    }
  };

  ...

  map<const char*, int, strCmp> ages;
  ages["Homer"] = 38;
  ages["Marge"] = 37;
  ages["Lisa"] = 8;
  ages["Maggie"] = 1;
  ages["Bart"] = 11;

  while( !ages.empty() ) {
    cout << "Erasing: " << (*ages.begin()).first << ", " << (*ages.begin()).second << endl;
    ages.erase( ages.begin() );
  }

When run, the above code displays:

  Erasing: Bart, 11
  Erasing: Homer, 38
  Erasing: Lisa, 8
  Erasing: Maggie, 1
  Erasing: Marge, 37
Related topics: