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

一曲冷凌霜 提交于 2019-12-22 08:27:10

问题


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;
}

回答1:


Because if find returns the end iterator and you dereference it you are triggering undefined behavior, which means that your program may do whatever - happen to work, work incorrectly, plain crash. This is a general rule of all C++ containers - the end iterator is just a placeholder for a "one past last" element, used as an end condition for loops or to signal that an element does not exist; you aren't meant to dereference it.

If you want a more compact way to check if an element is present, just use set.count(x).




回答2:


The problem is that

Test case 10 input

19268
3 7401  //first search without any input

if the very first input is 3 and for the search of element

set<int>::iterator it=s.find(x); //Returns end iterator

and when you deference the value of end() it will return exception

if(*it==x)


来源:https://stackoverflow.com/questions/45119362/why-is-it-necessary-to-to-use-set-findx-set-end-while-finding-an-element

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!