HackerRank C++ Sets-STL




Sets are a part of the C++ STL. Sets are containers that store unique elements following a specific order. Here are some of the frequently used member functions of sets:

Declaration:

sets; //Creates a set of integers.
Size:

int length=s.size(); //Gives the size of the set.
Insert:

s.insert(x); //Inserts an integer x into the set s.
Erasing an element:

s.erase(val); //Erases an integer val from the set s.
Finding an element:

set::iterator itr=s.find(val); //Gives the iterator to the element val if it is found otherwise returns s.end() .
Ex: set::iterator itr=s.find(100); //If 100 is not present then it==s.end().
Coming to the problem, you will be given Q queries. Each query is of one of the following three types:

: Add an element x to the set.
: Delete an element x from the set. (If the number is not present in the set, then do nothing).
: If the number x is present in the set, then print "Yes"(without quotes) else print "No"(without quotes).



  1. #include <cmath>
  2. #include <cstdio>
  3. #include <vector>
  4. #include <iostream>
  5. #include <set>
  6. #include <algorithm>
  7. using namespace std;
  8. int main()
  9. {
  10. /* Enter your code here. Read input from STDIN. Print output to STDOUT */
  11. int n;
  12. set<int>s;
  13. for(int i=0;i<n;i++)
  14. {
  15. int a;
  16. cin>>a;
  17. s.insert(a);
  18. }
  19. cin>>n;
  20. for(int i=0;i<n;i++)
  21. {
  22. int q,t;
  23. cin>>t>>q;
  24. switch(t)
  25. {
  26. case 1:
  27. {
  28. s.insert(q);
  29. break;
  30. }
  31. case 2:
  32. {
  33. s.erase(q);
  34. break;
  35. }
  36. case 3:
  37. {
  38. set<int>::iterator itr=s.find(q);
  39. if(itr==s.end())
  40. cout<<"No"<<endl;
  41. else
  42. cout<<"Yes"<<endl;
  43. break;
  44. }
  45. }
  46. }
  47. return 0;
  48. }
Please click on the like button if it worked

Solution not working or have any suggestions? Please send an email to [email protected]


donate a cup of tea :)


Join Our Facebook Group

Share this solution






codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube