In C++, a multimap is a container that stores elements where each element has a key value and a mapped value. Unlike maps, multimaps allow multiple key-value pairs with the same key. In this article, we will learn how to delete multiple key-value pairs from a multimap in C++.
Example
Input: myMultimap = { {Student 1: 90}, {Student 1: 78}, {Student 2: 90}, {Student 3: 92}, {Student 4: 69} } // deleting Student1 and Student2 Output: myMultimap = { {Student 3: 92}, {Student 4: 69} }
Remove Multiple Key-Value Pairs From a Multimap
We can store the keys of the elements that we want to delete from the multimap in a vector. We can then iterate the vector and delete the elements associated with the keys using the std::multimap::erase() function.
C++ Program to Erase Multiple Key-Value Pairs from a Multimap
// C++ Program to show how to delete Multiple Key-Value // pairs from the Multimap #include <iostream> #include <map> #include <vector> using namespace std;
int main()
{ // Create a multimap
multimap< int , string> myMultimap;
myMultimap.insert(make_pair(1, "Apple" ));
myMultimap.insert(make_pair(2, "Banana" ));
myMultimap.insert(make_pair(1, "Mango" ));
myMultimap.insert(make_pair(3, "Peach" ));
myMultimap.insert(make_pair(2, "Grape" ));
// Create a vector to store keys of elements to be
// deleted
vector< int > keys = { 1, 2 };
// Iterate over the vector and delete elements from the
// multimap
for ( int key : keys) {
myMultimap.erase(key);
}
// Print the remaining elements in the multimap
for ( auto it = myMultimap.begin();
it != myMultimap.end(); ++it) {
cout << it->first << " => " << it->second << '\n' ;
}
return 0;
} |
3 => Peach
Time complexity: O(M log N), where N is the size of the multimap and M is the number of elements with the specified keys.
Space Complexity: O(M)