set 中对象元素插入与查找

来源:互联网 发布:莫知我哀的莫的用法 编辑:程序博客网 时间:2024/06/10 06:46

使用 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 () 即可。


原创粉丝点击