Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ STL map::erase a non-existing key

Tags:

c++

key

map

stl

erase

Regarding the C++ STL map, erasing by key:-

 size_type map::erase ( const key_type& x ); 

Is it legal to erase a non-existing key? i.e. is the snippet below ok?

map<char,int> mymap; mymap['c']=30; mymap.erase('c'); mymap.erase('c'); mymap.erase('D'); 

Cheers

like image 974
fuad Avatar asked Mar 30 '09 01:03

fuad


People also ask

How do I delete a map key?

To delete a key from a map, we can use Go's built-in delete function. It should be noted that when we delete a key from a map, its value will also be deleted as the key-value pair is like a single entity when it comes to maps in Go.

How do I delete a key-value pair in maps?

Using erase() : erase() is used to erase the pair in map mentioned in argument, either its position, its value or a range of number. erase(key) : Erases the key-value pair using key mentioned in its argument.

How do I remove a specific element from a map in C++?

map::erase() is a built-in function in C++ STL which is used to erase element from the container. It can be used to erase keys, elements at any specified position or a given range. Parameters: The function accepts one mandatory parameter key which specifies the key to be erased in the map container.

How do you remove items from std::map?

The standard approach to remove elements from a map is using the std::map::erase member function. It offers several overload versions. The first overload version accepts an iterator pointing to an element that needs to be removed from the map.


1 Answers

Yes, in fact, std::map::erase() returns a size_type which indicates the number of keys erased. Thus it returns 0 for nothing erased and 1 for something erased for a map.

like image 178
rlbond Avatar answered Sep 27 '22 20:09

rlbond