为什么在查找元素时必须使用set.find(x)!= set.end()。 [英] Why is it necessary to to use set.find(x) != set.end() while finding an element.
问题描述
我想知道使用 *(set.find(x))== x
而不是 set有什么问题.find(x)!= set.end()
。
通常可以,但是在尝试对Hackerrank提问时(问题:链接) 。
此代码为所有测试用例提供CA:
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;}
但这不会无法用于2个测试用例。测试用例文件太大,尝试检查该大文件没有用。 :-
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;
}
推荐答案
因为如果 find
返回 end
迭代器,您取消引用它会触发未定义的行为,这意味着您的程序可能会做任何事情-可以正常工作,工作不正确,普通崩溃。这是所有C ++容器的一般规则- end
迭代器只是一个过去一个元素的占位符,用作循环的结束条件或表示元素不存在;您无意取消引用它。
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.
如果您想以更紧凑的方式检查元素是否存在,只需使用 set.count(x)
。
If you want a more compact way to check if an element is present, just use set.count(x)
.
这篇关于为什么在查找元素时必须使用set.find(x)!= set.end()。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!