Remove a key from a C++ map

c++, dictionary

Solution

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

Problem

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

Original source