In C++, a map container stores the collection of data in the form of a key and a value pair and this data is sorted on the basis of the key. In this article, we will learn how to delete multiple key-value pairs from a map in C++ STL.
Example:
Input: myMap = {{“apple”, 1}, {“banana”, 2}, {“cherry”, 3}}; Delete the key-value pairs {“apple”, 1}, {“cherry”, 3} Output: res={{"banana" : 2}}
Deleting Multiple Key-Value Pairs from Map in C++
If we want to delete multiple key-value pairs from a std::map, we can store the keys in the vector and then iterate the vector and keep deleting the keys using the std::map::erase() function.
C++ Program to Delete Multiple Key-Value Pairs from Map
C++
// C++ Program to illustrate how to delete multiple // key-value pairs from a map #include <iostream> #include <map> #include <vector> using namespace std;
int main()
{ // Creating a map of string and int
map<string, int > myMap = { { "apple" , 1 },
{ "banana" , 2 },
{ "cherry" , 3 } };
// keys do be deleted
vector<string> del({ "apple" , "cherry" });
// deleting elements
for ( auto key : del) {
myMap.erase(key);
}
// Displaying the map elements
for ( auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << " " << it->second << endl;
}
return 0;
} |
Output
banana 2
Time Complexity: O(M log N), where M is the number of elements to be deleted and N is the size of map.
Space Complexity: O(M)