为什么在查找元素时需要使用 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()
. 它通常有效,但在尝试在黑客兰克上提问时(问题:链接(。 此代码为所有测试用例提供 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)
相关文章:
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- set::find 查找不存在的元素
- std::set<Key,Compare,Allocator>::find() 函数使用"<"运算符而不是"=="运算符背后的直觉是什么?
- 使用 find() 通过 std::set 的迭代器将不起作用。出了什么问题?
- 为什么在查找元素时需要使用 set.find(x) != set.end()
- C ++设置与结构,set.find()函数使错误'invalid comparator'
- 为什么对排序向量进行的二进制搜索比STD :: SET FIND慢
- 为什么我的 std::set find() 不起作用
- std::set::find异常保证
- 调用 std::set<Type*>::find 时避免const_cast
- C++std::set Find函数重载==运算符
- 如何在 std::set 中为 FIND 和 ORDER 定义不同的条件
- set::find()找不到集合中的键
- 如何使 set:: find() 适用于自定义类对象
- 为什么 std::set<>::find 返回一个 const?
- C ++ map/set 迭代器不能使用 .find 取消引用
- Std::set::find与Std::find在Std::set上使用const
- std::<classtype>set.find(element) 是否使用类中的 == 运算符来比较元素?
- set::find 和 std::find 都无法在一个集合中找到一些双元素
- 对set使用find()函数