Open In App

How to Replace All Occurences of an Element in a Set in C++?

Last Updated : 05 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program to illustrate how to replace all occurences
// of a specific element in a set
#include <iostream>
#include <set>
using namespace std;
  
int main()
{
    // creating a set
    set<int> mySet = { 1, 2, 3, 2, 4, 5, 2 };
  
    // Printing the initial set
    cout << "Before replacement: ";
    for (int elem : mySet) {
        cout << elem << " ";
    }
    cout << endl;
  
    int target = 2; // Element to replace
    int replacement = 6; // Replacement element
  
    // Find and Erase the target element
    auto it = mySet.find(target);
    if (it != mySet.end()) {
        // Remove the target element
        mySet.erase(it);
  
        // Insert the Replacement element
        mySet.insert(replacement);
    }
    else {
        cout << target << " not found in the set" << endl;
    }
  
    // Print the set after replacement
    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)



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads