Advertisement
momo2345

set operators

Aug 13th, 2020
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. //Initial Template for C++
  2.  
  3. #include <bits/stdc++.h>
  4. using namespace std;
  5.  
  6. set<int> setInsert(int arr[],int n); //Function to insert elements of array into a set and return a set
  7.  
  8.  
  9. void setDisplay(set<int>s); //function to print the elements of the set
  10.  
  11.  
  12. void setErase(set<int>&s,int x); //function to erase x from set if it exists
  13.  
  14.  
  15.  // } Driver Code Ends
  16.  
  17.  
  18. //User function Template for C++
  19.  
  20.  
  21. set<int> setInsert(int arr[],int n)
  22. {
  23.     set<int>s;
  24.     for(int i=0; i<n; i++)
  25.    
  26.     //Your code here to insert arr into s
  27.     s.insert(arr[i]);
  28.    
  29.     return s;
  30.    
  31. }
  32.  
  33.  
  34. void setDisplay(set<int>s)
  35. {
  36.     //Your code here to display elements of s
  37.     for(auto u: s) cout<<u<<" ";
  38.     cout<<endl;
  39. }
  40.  
  41.  
  42. void setErase(set<int>&s,int x)
  43. {
  44.    //write if condition here
  45.    if(s.count(x)==1){
  46.        s.erase(x);
  47.     cout<<"erased "<<x;
  48.    }
  49.     //write else condition here
  50.     else
  51.     cout<<"not found";
  52.    
  53.    
  54.     cout<<endl;
  55. }
  56.  
  57. // { Driver Code Starts.
  58.  
  59. int main() {
  60.     int t;
  61.     cin>>t;
  62.     while(t--)
  63.     {
  64.         int n;
  65.         cin>>n;
  66.         int arr[n]; //array of size n
  67.         for(int i=0;i<n;i++)
  68.         cin>>arr[i]; //Input the array
  69.        
  70.         set<int>s=setInsert(arr,n); //call the insert function that returns a set
  71.         setDisplay(s);// display the inserted set
  72.         int x;
  73.         cin>>x; //x element that needs to be erased from set
  74.        
  75.         setErase(s,x); //try to erase x from set
  76.         setDisplay(s); //print the set after erase operation
  77.        
  78.        
  79.     }
  80.     return 0;
  81. }
  82.   // } Driver Code Ends
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement