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

WBOY
Release: 2023-08-27 23:29:02
forward
1314 people have browsed it

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  #include  using namespace std; int main(){ set s; set::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"<
        
Copy after login

Input

7 1 5 1 8 1 3 2 8 1 9 3 8 3 3
Copy after login

Output

No Yes
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!