How to Remove a Specific Pair From a Multimap in C++?
Last Updated :
05 Mar, 2024
In C++, a multimap is a container that can store multiple key-value pairs, where each key can be associated with multiple values. In this article, we will learn how to remove all occurrences of a specific key-value pair from a multimap in C++.
Example
Input:
myMultimap = {{1, “one”}, {2, “two”}, {2, “two”}, {3, “three”}};
Key-Value Pair to Remove = {2, “two”};
Output:
myMultimap = {{1, “one”}, {3, “three”}};
Remove a Specific Pair From a Multimap in C++
To remove a specific pair from a std::multimap, we can use the std::multimap::equal_range function to get a range of iterators representing all occurrences of the key, and then use the std::multimap::erase function to remove each occurrence of the key-value pair.
C++ Program to Remove a Specific Pair From a Multimap
C++
#include <iostream>
#include <map>
using namespace std;
int main()
{
multimap< int , string> myMultimap = { { 1, "one" },
{ 2, "two" },
{ 2, "two" },
{ 3, "three" } };
int keyToRemove = 2;
string valueToRemove = "two" ;
auto range = myMultimap.equal_range(keyToRemove);
for ( auto it = range.first; it != range.second;) {
if (it->second == valueToRemove) {
it = myMultimap.erase(it);
}
else {
++it;
}
}
cout << "Multimap after removing the key-value pair:"
<< endl;
for ( const auto & pair : myMultimap) {
cout << pair.first << " => " << pair.second << endl;
}
return 0;
}
|
Output
Multimap after removing the key-value pair:
1 => one
3 => three
Time complexity: O(M *log N), where M is the count of elements associated with a particular key and N is the total number of elements in the multimap.
Space Complexity: O(N)
Share your thoughts in the comments
Please Login to comment...