Home >Backend Development >C++ >C++ program for inserting, deleting and searching in set STL

C++ program for inserting, deleting and searching in set STL

WBOY
WBOYforward
2023-08-27 23:29:021410browse

C++程序用于在set STL中插入、删除和查找

Suppose we have a collection data structure of integer type data. On our standard input, we provide n queries. In each query (each row) we have two elements. The first is the operator and the second is the element. The operation is as follows -

  • Insert. This will insert the element into the collection

  • remove it. This will remove the element from the collection if it exists

  • Search. This will search the collection for the element and display "Yes" if present, otherwise "No".

So if the input is something like n = 7, then the query = [[1,5],[1,8],[1,3],[2,8], [1,9],[3,8],[3,3]], then the output will be [No, Yes] because 8 does not exist in the set, but 3 does.

To solve this problem, we will follow the following steps -

  • Define a collection s
  • Define a set of iterators "it" to iterate over s
  • q := Number of queries
  • When q is not zero, reduce q after each iteration and perform the following operations:
    • Get the query type qt
    • for qt
      • If qt is 1, then insert x s
        • Out of the block
      • If qt is 2, then remove x# from s
          ##Come out of the block
      • If qt is 3,
        • Call find(x) inside it
        • If it matches The last element of s, then:
          • Print NO
        • Otherwise
          • Print YES
        • From Out of the block
Example

Let us see the following implementation for 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

The above is the detailed content of C++ program for inserting, deleting and searching in set STL. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete