Open In App

How to Remove a Specific Pair From a Multimap in C++?

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++ program to illustrate how to remove the specific key
// value pair from a multimap
#include <iostream>
#include <map>
using namespace std;
  
int main()
{
    // Creating a multimap
    multimap<int, string> myMultimap = { { 1, "one" },
                                         { 2, "two" },
                                         { 2, "two" },
                                         { 3, "three" } };
  
    // Key-value pair to remove
    int keyToRemove = 2;
    string valueToRemove = "two";
  
    // Getting the range of the key
    auto range = myMultimap.equal_range(keyToRemove);
  
    // Removing all occurrences of the key-value pair
    for (auto it = range.first; it != range.second;) {
        if (it->second == valueToRemove) {
            it = myMultimap.erase(it);
        }
        else {
            ++it;
        }
    }
  
    // Printing the multimap after removing the key-value
    // pair
    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)


Article Tags :