- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to delete an element from the Set by passing its value in C++
Here we will see how to delete one element from set by passing the value as argument. So if the set is like {10, 20, 30, 50, 60, 80, 90, 100, 120, 200, 500}, and we want to delete 90, it will be: {10, 20, 30, 50, 60, 80, 100, 120, 200, 500}
In set each element can occur only once and they are arranged. The value of the element cannot be modified when it is added, so this is immutable. Though we can add or remove elements from it.
We can use the erase() method to do this task.
Example
#include<iostream> #include<set> using namespace std; void dispSet(set<int> myset) { set<int>::iterator it; for (it = myset.begin(); it != myset.end(); ++it) cout << ' ' << *it; cout << '\n'; } void deleteUsingValue(set<int> myset, int del_element) { cout << "Set before deletion:"; dispSet(myset); myset.erase(del_element); cout << "Set after deleting "<< del_element<< ": "; dispSet(myset); } int main() { set<int> tempSet; int arr[] = {10, 20, 30, 50, 60, 80, 90, 100, 120, 200, 500}; int n = sizeof(arr)/sizeof(arr[0]); for (int i = 0; i < n; i++) tempSet.insert(arr[i]); int del_element = 90; deleteUsingValue(tempSet, del_element); }
Output
Set before deletion: 10 20 30 50 60 80 90 100 120 200 500 Set after deleting 90: 10 20 30 50 60 80 100 120 200 500
Advertisements