Remove a key from a C++ map
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
Solution 1:
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
Solution 2:
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" ) ;
}