In C++, multisets are associative containers similar to sets, but unlike sets, they allow the users to store duplicate elements. In this article, we learn how to replace all the occurrences of a specific element in a multiset in C++.
Example
Input:
myMultiset = { 1,2,2,2,3,4,5 }
Output:
myMultiset = {1,3,4,5,6,6,6} // Element 2 got replaced by element 6
Replace All Occurrences of an Element in a Multiset in C++
To replace all the occurrences of an element in a multiset, we can use the combination of std::multiset::erase(), std::multiset::count(), and std::multiset::insert() functions.
Algorithm
1. Find the count the occurrences of the element we want to replace using count() function and store it in variable num.
2. Erase all the occurences of the element using erase() function.
3. Run a for loop n times to insert the new element n times using insert() function.
C++ Program to Replace All Occurrences of an Element in a Multiset
// C++ program to demonstrate the replacement of all // occurrences of a specific element in a multiset #include <iostream> #include <set> using namespace std;
int main()
{ // Example multiset
multiset< int > ms = { 1, 2, 2, 2, 3, 4, 5 };
// Element to replace
int elementToReplace = 2;
// Element to replace with
int replacementElement = 6;
// Get the count of occurrences of the element to
// replace
int count = ms.count(elementToReplace);
// Print the original multiset
cout << "Before Replacement: " ;
for ( int element : ms) {
cout << element << " " ;
}
cout << endl;
// Erase all occurrences of the element to replace
ms.erase(elementToReplace);
// Insert the replacement element with the desired count
for ( int i = 0; i < count; ++i) {
ms.insert(replacementElement);
}
// Print the updated multiset
cout << "After Replacement: " ;
for ( int element : ms) {
cout << element << " " ;
}
cout << endl;
return 0;
} |
Before Replacement: 1 2 2 2 3 4 5 After Replacement: 1 3 4 5 6 6 6
Time Complexity: O(N logN) where N is the number of elements in the multiset.
Auxilary Space : O(1)
Note: The order of the elements in the multiset will not be preserved after this operation. Because multiset maintains a sorted order of elements.