![]() |
VOOZH | about |
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
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.
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.
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.