C++ program to insert delete and find from set STL


Suppose we have a set data structure for integer type data. In our standard input we provide n queries. In each query (in each line) we have two elements. First one is the operator, second one is the element. The operations are like below −

  • Insert. This will insert the element into the set

  • Delete. This will delete the element from the set (if exists)

  • Search. This will search the element into the set, if present show Yes, otherwise No.

So, if the input is like n = 7, queries = [[1,5],[1,8],[1,3],[2,8],[1,9],[3,8],[3,3]], then the output will be [No, Yes] because 8 is not present in set and 3 is present.

To solve this, we will follow these steps −

  • Define one set s
  • Define one set iterator 'it' to iterate through s
  • q := number of queries
  • while q is non-zero, decrease q after each iteration, do:
    • take the query type qt
    • for qt
      • if qt is 1, insert x s
        • Come out from the block
      • if qt is 2, delete x from s
        • Come out from the block
      • if qt is 3,
        • call find(x) inside the it
        • if it is same as last element of s, then:
          • print NO
        • Otherwise
          • print YES
        • Come out from the block

Example

Let us see the following implementation to get better understanding −

#include <iostream>
#include <set>
using namespace std;
int main(){
    set<int> s;
    set<int>::iterator it;
    int q,x;
    int qt;
    cin >> q;
    while(q--){
        cin>>qt>>x;
        switch(qt){
            case 1:s.insert(x);
                    break;
            case 2:s.erase(x);
                    break;
            case 3:it=s.find(x);
                    if(it==s.end())
                        cout<<"No"<<endl;
                    else
                        cout<<"Yes"<<endl;
                    break;
        }
    }
    return 0;
}

Input

7
1 5
1 8
1 3
2 8
1 9
3 8
3 3

Output

No
Yes

Updated on: 07-Oct-2021

404 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements