samedi 15 juillet 2017

Why is it necessary to to use set.find(x) != set.end() while finding an element.

I am wondering what is wrong when I use *(set.find(x)) == x instead of set.find(x)!=set.end(). It usually works but while attempting a question on Hackerrank (question : link). This code gives CA for all test cases :

int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */   

set<int>s;
int n,x,y;
cin >> n;
while(n--){
    cin >> y >> x;
    if(y==1)
        s.insert(x);
    else if(y==2)
        s.erase(x);
    else {
        set<int>::iterator it=s.find(x);
        if(it != s.end())
            cout << "Yes" <<endl;
        else cout << "No" <<endl;
    }
}
return 0;}

But this doesn't work for 2 test cases. The test case file is too big and it's no use trying to check that huge file. :-

 #include <cmath>
 #include <cstdio>
 #include <vector>
 #include <iostream>
 #include <set>
 #include <algorithm>
 using namespace std;


 int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */

set<int>s;
int n,x,y;
cin >> n;
while(n--){
    cin >> y >> x;
    if(y==1)
        s.insert(x);
    else if(y==2)
        s.erase(x);
    else {
        set<int>::iterator it=s.find(x);
        if(*it==x)
            cout << "Yes" <<endl;
        else cout << "No" <<endl;
    }
}
return 0;
}

Aucun commentaire:

Enregistrer un commentaire