77

I would like to remove a key from a STL map. However, map.erase() doesn't do anything. How would I go about doing this

1
  • 26
    Erase does something. How are you using it? And what is making you believe that it isn't doing anything? Commented Apr 6, 2012 at 4:05

2 Answers 2

115

It depends entirely on how you're calling it but it sounds like you may be using the first,last option. If you are, you need to keep in mind that it erase elements starting at first, up to but excluding last. Provided you follow that rule, iterator-based removal should work fine, either as a single element or a range.

If you're erasing by key, then it should also work, assuming the key is in there of course.

The following sample code shows all three methods in action:

#include <iostream> #include <map> int main (void) { std::map<char,char> mymap; std::map<char,char>::iterator it; mymap['a'] = 'A'; mymap['b'] = 'B'; mymap['c'] = 'C'; mymap['d'] = 'D'; mymap['e'] = 'E'; mymap['f'] = 'F'; mymap['g'] = 'G'; mymap['h'] = 'H'; mymap['i'] = 'I'; it = mymap.find ('b'); // by iterator (b), leaves acdefghi. mymap.erase (it); it = mymap.find ('e'); // by range (e-i), leaves acd. mymap.erase (it, mymap.end()); mymap.erase ('a'); // by key (a), leaves cd. mymap.erase ('z'); // invalid key (none), leaves cd. for (it = mymap.begin(); it != mymap.end(); it++) std::cout << (*it).first << " => " << (*it).second << '\n'; return 0; } 

which outputs:

c => C d => D 
Sign up to request clarification or add additional context in comments.

1 Comment

@paxdiablo I really amazed by your work. As always your every answer is just clear & informative. Thanks.
17

You would have to find the iterator first

map.erase( ITERATOR ) ; 

To make this safe, you need to make sure that ITERATOR exists, however. Par example:

#include <stdio.h> #include <map> using namespace std ; int main() { map<int,int> m ; m.insert( make_pair( 1,1 ) ) ; map<int,int>::iterator iter = m.find(1) ; if( iter != m.end() ) m.erase( iter ); else puts( "not found" ) ; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.