先说结论,用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