首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

C++的set中的find函数,具体什么原理啊总不对呢,该如何处理

2012-10-13 
C++的set中的find函数,具体什么原理啊,总不对呢#include iostream#include string#include setusing

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中相等定义为
a>b且b<a则a==b
所以程序输出no!是正确的

a>b且b<a则a==b
改为
a<b且b<a则a==b

[解决办法]
向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都为假时,它们相等。

热点排行