C++STL中set不存在对应元素时set.find的返回值

先说结论,用find函数查找不存在的元素时,返回和 end() 方法一样的迭代器

1.

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
	set<int> a;
	for(int i=0;i<10;i++){  //a中元素为 0 1 2 3 4 5 6 7 8 9
		a.insert(i);
	}
	set<int>::iterator it=a.find(10);  //指向元素“10”的位置(实际上10不存在)
	cout<<*it<<endl;
	return 0;
}
此时输出结果为10

明明set中不存在“10”,为什么find的结果是10?

也许是找不到元素时,指向最后一个元素的末尾?虽然按原理来说不可能,但是还是试一试

2.

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
	set<int> a;
	for(int i=100;i<110;i++){         //100 101 102 103 104 105 106 107 108 109 共10个元素
		a.insert(i);
	}
	set<int>::iterator it=a.find(1);
	cout<<a.size()<<endl;             //输出10
	cout<<*it<<endl;                  //输出10
	return 0;
}

由此可见,可能与元素个数有关

3.

#include <iostream>
#include <algorithm>
#include <set>
using namespace std;
int main()
{
	set<int> a;
	for(int i=0;i<10;i+=2){      //0 2 4 6 8 共五个元素
		a.insert(i);
	}
	set<int>::iterator it=a.find(100);
	cout<<a.size()<<endl;       //输出5
	cout<<*it<<endl;            //输出5
	return 0;
}

 再次验证得到肯定答案

应用:哈希判重

if (s.find(x) != s.end()) {
                return true;
            }
            s.insert(x);

s集合中不存在x,则将x放进集合

一旦出现重复,返回true

  • 9
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值