关于set的自定义比较函数的使用及结构体的上下二分用法

如果set的类型是个结构体
我们需要定义重载函数

***set 容器模版需要3个泛型参数,如下:

    template <class Key,
          class Compare = less <key>,
          class Alloc = alloc>
    class set {
    ...
    };

第一个是元素类型,必选;
第二个指定元素比较方式,缺省为 Less, 即使用 < 符号比较;
第三个指定空间分配对象,一般使用默认类型。
因此:
(1) 如果第2个泛型参数你使用默认值的话,你的自定义元素类型需要重载 < 运算操作;
(2) 如果你第2个泛型参数不使用默认值的话,则比较对象必须具有 () 操作,即:
bool operator()(const T &a, const T &b)*

struct node{
    int l,r;
    bool operator<(const node &R)const{
        return l<R.l||(l==R.l&&r<R.r);
    }
    node(int a,int b):l(a),r(b){}
};

如果结构体本身就有重载<函数
用的时候只需写

set<node>s;

即可
如果本身比较类型没有运算符重载函数
我们需要重载()

struct node{
    int l,r;
    node(int a,int b):l(a),r(b){}
};
struct cmp
{
    bool operator()(const node &L,const node &R)const{
        return L.l<R.l||(L.l==R.l&&L.r<R.r);
    }
};

那么其对应的声明方法是

set<node,cmp>s;

set中还可以使用lower_bound()和upper_bound()
那么如何对结构体二分呢?

如果我们已经定义了一个比较函数那么lower_bound()或是upper_bound()会根据我们写入的重载比较函数
或是比较结构体去比较寻找
例如:

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
struct node{
    int l,r;
    node(int a,int b):l(a),r(b){}
};

struct cmp
{
    bool operator()(const node &L,const node &R)const{
        return L.l<R.l||(L.l==R.l&&L.r<R.r);
    }
};

int main()
{
    set<node,cmp>s;
    s.insert(node(1,2));
    s.insert(node(1,3));
    s.insert(node(1,4));
    s.insert(node(5,2));
    s.insert(node(3,5));
    set<node>::iterator  it = s.lower_bound(node(1,5));// 输出 3 5
    cout<<it->l<<" "<<it->r<<endl;

    set<node>::iterator  it = s.lower_bound(node(1,2));// 输出 1 2
    cout<<it->l<<" "<<it->r<<endl;

    set<node>::iterator  it = s.lower_bound(node(1,0));// 输出 1 2
    cout<<it->l<<" "<<it->r<<endl;

    set<node>::iterator  it = s.upper_bound(node(1,2));// 输出 1 3
    cout<<it->l<<" "<<it->r<<endl;
    return 0;
}

所以完全是可以那结构体二分的!
需要注意的就是比较函数中涉及到几个成员变量那么关于二分的参数结构体就得指定几个参数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值