VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-replace-a-specific-pair-in-a-multimap-in-cpp/

⇱ How to Replace a Specific Pair in a Multimap in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Replace a Specific Pair in a Multimap in C++?

Last Updated : 23 Jul, 2025

in C++, multimap is similar to a map that stores the data in the key-value format where duplicate keys are allowed. In this article, we will learn how to replace a specific pair in a multimap in C++.

Example

Input: 
myMultimap = {{1, “one”}, {2, “two”}, {2, “two”}, {3, “three”}};
Key-Value Pair to Replace = {2, “two”};
To be Replaced with = {5, "five"}

Output:
myMultimap = {{1, “one”}, {3, “three”}, {5, "five"}, {5, "five"}};

Replace a Specific Pair in a Multimap in C++

To replace a specific pair in a std::multimap, we can use the std::multimap::equal_range function to get a range of iterators representing all occurrences of the key, find the required pair, delete it, and then insert a new one.

Approach

  • Get the range of the old key using the equal_range() function.
  • Iterate over the range of the old key.
  • In each iteration, check if the value of the current pair matches the value you want to replace.
  • If it matches, insert a new pair into the multimap with the new key and new value.
  • Remove all occurrences of the old key-value pair from the multimap using erase() function.

C++ Program to Replace a Specific Pair in a Multimap


Output
Multimap after replacing the key:
1 => one
3 => three
4 => four
4 => four

Time Complexity: O(K Log N), where K is the number of matching elements, and N is the size of the multimap.
Space Complexity: O(K)



Comment