c++ 标准模板库(STL) 谓词(predicate) 详细介绍

1. 定义
The Predicate parameter is used whenever an algorithm expects a function object that when applied to the result of dereferencing the corresponding iterator returns a value testable as true. In other words, if an algorithm takes Predicate pred as its argument and first as its iterator argument, it should work correctly in the construct if (pred(*first)){...}. The function object pred shall not apply any non-constant function through the dereferenced iterator. This function object may be a pointer to function, or an object of a type with an appropriate function call operator.
当一个算法需要一函数对象,去应用于解引用(deferencing)迭代器(deferencing 解释: int p;将定义一个指向整数的指针,并p取消引用该指针,这意味着它将实际检索p指向的数据。)的结果,谓词参数返回一个testable值为true。换句话说,换句话说, 如果算法将谓词 pred 作为其参数,first参数是迭代参数,则如果 (pred (* first)) {..} , 它应该在构造中正常工作。函数对象 pred 不应通过解引用迭代器应用于任何非定常(non-constant)函数。此函数对象可以是指向函数的指针, 也可以是具有适当函数调用运算符的类型的对象。
2. 简单释义

如果你写的函数对象接受一个参数,那么就叫 一元函数对象
如果你写的函数对象接受两个参数,那么叫 二元函数对象
如果你写的函数对象或者普通函数接受一个参数,并且返回值是Bool,叫一元谓词
如果你写的函数对象或者普通函数接受二个参数,并且返回值是Bool,叫二元谓词
3. 举例说明
1) 一元谓词

//一元谓词 应用举例:find_if
class mycompare{
public:
    bool operator()(int v){
        if (v > 7){
            return true;
        }
        else{
            return false;
        }
    }
};

vector<int> v;
for (int i = 0; i < 10; i++){
    v.push_back(i);
}
vector<int>::iterator pos = find_if(v.begin(), v.end(), mycompare()); //匿名函数对象
if(pos == v.end()){
    cout << "没找到" << endl;
}
else{
cout << "找到:" << *pos << endl;
}
2)二元谓词

//二元函数对象 应用举例 : transform
class myplus{
public:
    int operator()(int v1,int v2){
        return v1 + v2;
    }
    
};

vector<int> v1,v2,v3;
for (int i = 0; i < 10; i++){
    v1.push_back(i);
    v2.push_back(i + 1);
}
transform(v1.begin(), v1.end(), v2.begin(), v3.begin(), myplus()); //匿名函数对象
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

giantmfc123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值