How to Delete Multiple Key-Value Pairs from a Map in C++?
Last Updated :
29 Feb, 2024
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++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
map<string, int > myMap = { { "apple" , 1 },
{ "banana" , 2 },
{ "cherry" , 3 } };
vector<string> del({ "apple" , "cherry" });
for ( auto key : del) {
myMap.erase(key);
}
for ( auto it = myMap.begin(); it != myMap.end(); ++it) {
cout << it->first << " " << it->second << endl;
}
return 0;
}
|
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)
Share your thoughts in the comments
Please Login to comment...