How to Replace All Occurences of an Element in a Set in C++?
Last Updated :
05 Mar, 2024
In C++, a set is an associative container that stores unique elements in a sorted order. In this article, we will learn how to replace all occurrences of a specific element in a set in C++.
Example:
Input:
mySet = {1,2,3,2,4,5,2};
target = 2
replacement = 6
Output:
After Replacement: 1 3 4 5 6
Replace All Occurrences of an Element in a Set in C++
To replace all occurrences of a given element in a std::set, we first need to find the target element using std::set::find and remove that element from the set using the std::set::erase
function. Then, we can insert the replacement element using the std::set::insert
function.
Note: STL set containers allows only the unique elements in some order. So the first occurence will be the only occurrence of the element in the set and the new elements will also be according to the prevoius order.
C++ Program to Replace All Occurrences of an Element in a Set
The below program demonstrates how we can replace all occurrences of a specific element in a set in C++ STL.
C++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet = { 1, 2, 3, 2, 4, 5, 2 };
cout << "Before replacement: " ;
for ( int elem : mySet) {
cout << elem << " " ;
}
cout << endl;
int target = 2;
int replacement = 6;
auto it = mySet.find(target);
if (it != mySet.end()) {
mySet.erase(it);
mySet.insert(replacement);
}
else {
cout << target << " not found in the set" << endl;
}
cout << "After Replacement: " ;
for ( int elem : mySet) {
cout << elem << " " ;
}
cout << endl;
return 0;
}
|
Output
Before replacement: 1 2 3 4 5
After Replacement: 1 3 4 5 6
Time Complexity: O(log n), here n is the number of elements in the set.
Auxilliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...