How to Replace All Occurrences of an Element in a Multiset in C++?
Last Updated :
08 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
multiset< int > ms = { 1, 2, 2, 2, 3, 4, 5 };
int elementToReplace = 2;
int replacementElement = 6;
int count = ms.count(elementToReplace);
cout << "Before Replacement: " ;
for ( int element : ms) {
cout << element << " " ;
}
cout << endl;
ms.erase(elementToReplace);
for ( int i = 0; i < count; ++i) {
ms.insert(replacementElement);
}
cout << "After Replacement: " ;
for ( int element : ms) {
cout << element << " " ;
}
cout << endl;
return 0;
}
|
Output
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.
Share your thoughts in the comments
Please Login to comment...