C++的set中的find函数,具体什么原理啊,总不对呢
#include <iostream>
#include <string>
#include <set>
using namespace std;
class one
{
public:
string a;
string b;
one(string a,string b):a(a),b(b){}
bool operator <(const one& a)const{return this-> b <a.b;}
/*bool operator ==(const one& a)const
{
return (this-> a==a.a)||(this-> b==a.b);
}*/
//这里如果改成{return this-> a <a.a;}输出就是find!
//我试过重载 “==”算符 但是 对find函数没有影响。
//我重载了“==”算符 发现 这个只对两个one实例比较的时候有影响。
};
int main()
{
one a1( "a ", "b ");
set <one> book;
book.insert(a1);
set <one> ::iterator iM=book.find(one( "a ", "a "));
if(iM!=book.end())
cout < < "find! " < <endl;
else
cout < < "no! " < <endl;
return 0;
}
//输出是 no!。
[解决办法]
[解决办法]
向set中添加的元素类型必须重载<操作符用来排序。排序满足以下准则:
1、非对称,若A<B为真,则B<A为假。
2、可传递,若A<B,B<C,则A<C。
3、A<A永远为假。
set中判断元素是否相等:
if(!(A<B || B<A)),当A<B和B<A都为假时,它们相等。