How to Delete a Pair from a Multimap in C++?
Last Updated :
06 Feb, 2024
In C++, multimap stores key-value pairs and for the same key there can be multiple values in a multimap. In this article, we will learn how to delete a pair from a multimap in C++.
Example
Input:
mpp={{"apple", 1},{"banana", 2},{"apple", 3}, {"orange", 4}}
keyToRemove=apple
valueToRemove=3
Output:
apple: 1
banana: 2
orange: 4
Remove a Pair from Multimap in C++
To delete a pair from multimap, we can use the std::multimap::erase() function with a combination of std::find_if().
First, create a custom binary predicate function to pass to the find_if() function to check for the matching key-value pair and find the iterator using the find_if() function. Then remove the pair using erase() by passing the iterator in it.
C++ Program to Delete a Pair from Multimap
C++
#include <algorithm>
#include <iostream>
#include <map>
using namespace std;
int main()
{
multimap<string, int > myMpp = {
{ "apple" , 1 },
{ "banana" , 2 },
{ "apple" , 3 },
{ "orange" , 4 },
};
string keyToRemove = "apple" ;
int valueToRemove = 3;
auto it = find_if(
myMpp.begin(), myMpp.end(), [&]( const auto & pair) {
return pair.first == keyToRemove
&& pair.second == valueToRemove;
});
if (it != myMpp.end()) {
myMpp.erase(it);
}
for ( const auto & pair : myMpp) {
cout << pair.first << ": " << pair.second << endl;
}
return 0;
}
|
Output
apple: 1
banana: 2
orange: 4
Time Complexity: O(N)
Auxiliary Space: O(1)
Note: We can also use equal_range
() with erase() function to delete a pair from multimap.
Share your thoughts in the comments
Please Login to comment...