How To Delete Multiple Key-Value Pairs From Multimap in C++?
Last Updated :
29 Feb, 2024
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++
#include <iostream>
#include <map>
#include <vector>
using namespace std;
int main()
{
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" ));
vector< int > keys = { 1, 2 };
for ( int key : keys) {
myMultimap.erase(key);
}
for ( auto it = myMultimap.begin();
it != myMultimap.end(); ++it) {
cout << it->first << " => " << it->second << '\n' ;
}
return 0;
}
|
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)
Share your thoughts in the comments
Please Login to comment...