STL map erase

Jul 1, 2010 at 12:58pm
If I use erase for a key that does not exist in the map, is it a problem or the function does not do anything and returns harmlessly?
For example
map.erase('b') where 'b' is not contained in the map. What will it do?
Jul 1, 2010 at 1:04pm
It can't remove what's not there. It can't break the map, if that's what you're asking.
Jul 1, 2010 at 1:32pm
Borrowed from stl_map.h:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
      /**
       *  @brief Erases elements according to the provided key.
       *  @param  x  Key of element to be erased.
       *  @return  The number of elements erased.
       *
       *  This function erases all the elements located by the given key from
       *  a %map.
       *  Note that this function only erases the element, and that if
       *  the element is itself a pointer, the pointed-to memory is not touched
       *  in any way.  Managing the pointer is the user's responsibilty.
       */
      size_type
      erase(const key_type& __x)
      { return _M_t.erase(__x); }

Jul 1, 2010 at 2:18pm
No I am just saying will it give an error when I call remove. I want to remove some key if it is in the map and not worry about it if it not in the map.Will erase accomplish that or first I should serach in the map and erase only if they key is found?
Jul 1, 2010 at 2:49pm
Come on. Did you read why I copied above? Look at the return value. Do you think based on that
that the function will crash if the key isn't found?
Jul 1, 2010 at 5:35pm
Thanks
Jul 1, 2010 at 6:01pm
Read the documentation here. It will tell you the same thing that jsmith indicates with his example.
http://cplusplus.com/reference/stl/map/erase/
Topic archived. No new replies allowed.