Let us say, we have a Map that contains,
As Key and Value pair.
Now, if you want to remove the entries from a Map, erase() and clear() Method can be used.
Let us look at the erase() Method first.
The erase() Method can be used to remove an item from the Map.
Let us say, we want to remove the entry where the Key is Five and Value is Is a Number.
#include <iostream> #include <map> using namespace std; int main() { map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} }; x.erase("Five"); for (auto i : x) { cout << "The Key is : " << i.first << " and the Value is :" << i.second << endl; } return 0; }
So, in the above code we have created a Map using braces {} and Key and Value pairs.
map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} };
And initialised to the variable x.
Now, we are supposed to delete the value of the Key, Five.
So, we have used the below way to update it.
x.Remove("Five");
And the entry for the Key Five is deleted for the Map.
And we get the below output,
The clear() Method can be used to remove all the elements from the Map.
#include <iostream> #include <map> using namespace std; int main() { map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} }; x.clear(); for (auto i : x) { cout << "The Key is : " << i.first << " and the Value is :" << i.second << endl; } return 0; }
So, in the above code we have created a Map using braces {} and Key and Value pairs.
map<string, string> x = { { "Five", "Is a Number" }, { "John", "Is a Name" }, { "C++", "Is a Language"} };
And initialised to the variable x.
And we have used the clear() method to remove all the elements from the Map.
x.clear()
And the print statement, prints an empty Map.