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

16 篇文章 0 订阅

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
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值