How to Replace Specific Element in Set in C++?
Last Updated :
12 Feb, 2024
Improve
In C++ STL (Standard Template Library), a set is a container that stores unique elements in a sorted order. In this article, we will learn how to replace a specific element in a set in C++.
Example:
Input:
Initial Set: 10 20 30
// Replace 20 with 25
Output:
Modified Set: 10 25 30
Replace Specific Element in a Set in C++
In C++, we can easily replace a specific element in a set by removing the old element using the std::set::erase() function and then insert the new element using the std::set::insert() function.
Syntax
set_name.erase(value_to_replace); // Erase the old element
set_name.insert(new_value); // Insert the new element
C++ Program to Replace Specific Element in a Set
Below is the Implementation of the above approach:
// C++ program to replace the specific element in a set
#include <iostream>
#include <set>
using namespace std;
int main()
{
// Create a set and insert elements
set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
// Print the initial set
cout << "Initial Set: ";
for (auto value : mySet) {
cout << value << " ";
}
cout << endl;
// Replace 20 with 25
mySet.erase(20); // Erase the old element
mySet.insert(25); // Insert the new element
// Print the modified set
cout << "Modified Set: ";
for (auto value : mySet) {
cout << value << " ";
}
cout << endl;
return 0;
}
// This code is contributed by Susobhan Akhuli
Output
Initial Set: 10 20 30 Modified Set: 10 25 30
Time Complexity: O(logN)
Space Complexity: O(1)
Note: The new element may not be placed in the same position as set elements are sorted in some order.