使用STL模板必须重载的运算符

来源:互联网 发布:华为mate10抢购软件 编辑:程序博客网 时间:2024/06/05 13:27

STL各种容器和算法的sort和find函数对重载运算符的调用情况:

1) 二叉树类型的容器的sort和find都会调用operator < 。

2)线性类型容器sort会调用operator <;线性容器使用std::find会调用operator ==。

需要非常注意重载<运算符,分类讨论要周全。不然重则会导致dump机问题,轻则会导致排序不对。

对于< 号的重载要满足严格弱序的要求。

严格弱序定义如下:

 x R x 为false

x R y => !(y R x)   另一种表示为    !(x R y) && !(y R x) 则 x=y

 x R y 且 y R z 则 x R z


下面调用find 函数测试在set中find调用了< 关系,(去掉注释,调用stl 标准的find函数会调用 == 关系)

#include <iostream>#include <set>using namespace std; struct s{    int x,y;    s(int xx,int yy):x(xx),y(yy){}    bool operator <(const s& tmp) const {        if(x < tmp.x){            return true;        }        else if(y < tmp.y){            return true;        }        return false;    } };set<s> ms;int main(){        ms.insert(s(31,41));        s test(31,41);        s test2(32,41);        if(test < test2){            cout<<" test<test2"<<endl;        }        //auto itt = find(ms.begin(),ms.end(),test);        auto itt = ms.find(test);        if(itt!= ms.end()){            cout<< "find the value: "<<itt->x<<endl;        }        else{             cout<<"not found"<<endl;        }}

0 0
原创粉丝点击