E. Changing/Accessing Map Elements
Any map element can be changed or accessed extremely easily. Simply utilise the same key that was used to insert the data.
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m["Harry"] = 1;
display(m);
Output:
The elements are:
Harry -> 2
Rohan -> 4
The elements are:
Harry -> 1
Rohan -> 4
F. Eliminating components from a map
A map’s components can be removed in a variety of ways. Any element can be removed from a map in logarithmic time, which is faster than the removal time for vectors or arrays but slower than the removal time for lists.
The erase() method can be used to remove elements from a map. Both keys and an iterator can be used with the erase() method to remove elements. When use the erase approach, the syntax is
map_name.erase(iterator);
//OR
map_name.erase(key);
Here, the key is the key of the key-value combination that needs to be deleted, and the iterator is a pointer to the location where the element is to be deleted from. Here’s an illustration of how to utilise the wipe() method with a key
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m.erase("Harry");
display(m);
Output:
The elements are:
Harry -> 2
Rohan -> 4
The elements are:
Rohan -> 4
Here’s an illustration of how to utilise the erase() method with a reference.
map<string, int> m = {{"Harry", 2}, {"Rohan", 4}};
display(m);
m.erase(m.begin()); //deletes the first element
display(m);
Output:
The elements are:
Harry -> 2
Rohan -> 4
The elements are:
Rohan -> 4