set 中对象元素插入与查找

使用 set::find 函数在 set 集合中寻找元素时,若元素定义了 operator < 方法,则使用此函数在 set 维护的红黑树中查找。否则编译时期报错。

还可以通过给 set 指定第二个泛型类型:彷函数(此时,不需要再定义 operator <)。如:

class ProcessInfoSortRule
{
public:
bool operator () (const ProcessInfo &pil, const ProcessInfo &pir) const
{
printf("ProcessInfoCmp:: operate () called.\r\n");
return (pil.pid < pir.pid);
}
};

set<ProcessInfo, ProcessInfoSortRule> infos; //使用 ProcessInfoSortRule 作为 infos 的排序规则。注意, set 接收的彷函数,必须满足规则:返回 true 表示比较的两个元素左边 < 右边。

以上两种方法,operator < 或彷函数,在插入元素时也会被用来寻找元素应该插入的位置。

上面彷函数的使用是给 set 传入了一个相关的类,另外一种用法是传入一个对象。

看下面这个类:

class LessThan
{
private:
int _bound;
public:
explicit LessThan(int bound)
:_bound(bound)
{

}
bool operator()(const ProcessInfo& l)
{
return l.pid < _bound;
}
};


bool (LessThan::* myLess)(const ProcessInfo&);
myLess = &LessThan::operator();

int count = count_if(infos.begin(), infos.end(), LessThan(100)); //此处的语法看起来奇怪,实际上这样写更易看懂


LessThan less(100);

int count = count_if(infos.begin(), infos.end(), LessThan(less)); //构建一个对象给 count_info 使用,count_info 只是要求在传入对象上面可以调用 operator () 即可。


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值