Open In App

How to Delete a Pair from a Multimap in C++?

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++ program to delete a pair from multimap
#include <algorithm>
#include <iostream>
#include <map>
  
using namespace std;
  
int main()
{
  
    // creating a mutimap
    multimap<string, int> myMpp = {
        { "apple", 1 },
        { "banana", 2 },
        { "apple", 3 },
        { "orange", 4 },
    };
  
    // Define the key and value to remove
    string keyToRemove = "apple";
    int valueToRemove = 3;
  
    // Find the element
    auto it = find_if(
        myMpp.begin(), myMpp.end(), [&](const auto& pair) {
            return pair.first == keyToRemove
                   && pair.second == valueToRemove;
        });
  
    // If found, erase it
    if (it != myMpp.end()) {
        myMpp.erase(it);
    }
  
    // Iterate and print remaining elements
    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.


Article Tags :