学习STL时发现手头的资料上没有说明元素未存在时的情况,CSDN前几篇文章似乎也没有说明。
能力有限,描述的可能不是很正确,见谅。
先说结论,用find函数查找不存在的元素时,函数的返回的值为set中元素的个数(表达的不准确,先看代码吧)
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;
}
再次验证得到肯定答案