How to Replace a Specific Pair in a Multimap in C++?
Last Updated :
05 Mar, 2024
Improve
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
// C++ Program to illustrate how to replace a specific
// key-value pair
#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 replace
int oldKey = 2;
string value = "two";
// New key
int newKey = 4;
string newValue = "four";
// Getting the range of the old key
auto range = myMultimap.equal_range(oldKey);
// Inserting new pairs with the new key and the same
// value
for (auto it = range.first; it != range.second; ++it) {
if (it->second == value) {
myMultimap.insert({ newKey, newValue });
}
}
// Removing all occurrences of the old key-value pair
myMultimap.erase(oldKey);
// Printing the multimap after replacing the key
cout << "Multimap after replacing the key:" << endl;
for (const auto& pair : myMultimap) {
cout << pair.first << " => " << pair.second << endl;
}
return 0;
}
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)