为什么在查找元素时需要使用 set.find(x) != set.end()

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

本文关键字:set find end 元素 查找 为什么      更新时间:2023-10-16

我想知道使用*(set.find(x)) == x时出了什么问题 而不是set.find(x)!=set.end(). 它通常有效,但在尝试在黑客兰克上提问时(问题:链接(。 此代码为所有测试用例提供 CA:

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 个测试用例。测试用例文件太大,尝试检查那个大文件是没有用的。:-

#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迭代器只是"过去最后一个"元素的占位符,用作循环的结束条件或指示元素不存在;你不应该取消引用它。

如果您想要一种更紧凑的方式来检查元素是否存在,只需使用set.count(x).

问题是

测试用例 10 输入

19268
3 7401  //first search without any input

如果第一个输入是 3 并且用于搜索元素

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

当你尊重 end(( 的值时,它将返回异常

if(*it==x)