How to Replace Specific Element in Set in C++?
Last Updated :
12 Feb, 2024
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++
#include <iostream>
#include <set>
using namespace std;
int main()
{
set< int > mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
cout << "Initial Set: " ;
for ( auto value : mySet) {
cout << value << " " ;
}
cout << endl;
mySet.erase(20);
mySet.insert(25);
cout << "Modified Set: " ;
for ( auto value : mySet) {
cout << value << " " ;
}
cout << endl;
return 0;
}
|
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.
Share your thoughts in the comments
Please Login to comment...